tags:

views:

120

answers:

2

I am working on integrating tor to my Delphi application; the whole story is explained in this link

After that I searched the internet then I found a code to switch new identity in PHP

 function tor_new_identity($tor_ip='127.0.0.1', $control_port='9051', $auth_code=''){
    $fp = fsockopen($tor_ip, $control_port, $errno, $errstr, 30);
    if (!$fp) return false; //can't connect to the control port

    fputs($fp, "AUTHENTICATE $auth_code\r\n");
    $response = fread($fp, 1024);
    list($code, $text) = explode(' ', $response, 2);
    if ($code != '250') return false; //authentication failed

    //send the request to for new identity
    fputs($fp, "signal NEWNYM\r\n");
    $response = fread($fp, 1024);
    list($code, $text) = explode(' ', $response, 2);
    if ($code != '250') return false; //signal failed

    fclose($fp);
    return true;
}

Can any one help me porting this to Delphi/Pascal

I don't know any PHP basics

thanks in advance

regards

+3  A: 

Warning: I haven't written this in an IDE, but any syntax errors should be easy to fix. The logic around "send a command, read a line, see if it's a 250 response code" should really be pulled out into a separate function. I haven't done so so the code resembles the original PHP a bit more closely. (I have a CheckOK because I couldn't stop myself.)

function CheckOK(Response: String): Boolean;
var
  Code: Integer;
  SpacePos: Integer;
  Token: String;
begin
  SpacePos := Pos(' ', Response);
  Token := Copy(Response, 1, SpacePos);
  Code := StrToIntDef(Token, -1);
  Result := Code <> 250;
end;

function TorNewIdentity(TorIP: String = '127.0.0.1'; ControlPort: Integer = 9051; AuthCode: String = ''): Boolean
var
  C: TIdTcpClient;
  Response: String;
begin 
  Result := true;

  C := TIdTcpClient.Create(nil);
  try
    C.Host := TorIP;
    C.Port := ControlPort;
    C.Connect(5000); // milliseconds

    C.WriteLn('AUTHENTICATE ' + AuthCode);
    // I assume here that the response will be a single CRLF-terminated line.
    Response := C.ReadLn;
    if not CheckOK(Response) then begin
      // Authentication failed.
      Result := false;
      Exit;
    end;

    C.WriteLn('signal NEWNYM');
    Response := C.ReadLn;
    if not CheckOK(Response) then begin
      // Signal failed.
      Result := false;
      Exit;
    end;
  finally
    C.Free;
  end; 
end;
Frank Shearar
There's one obvious error in your CheckOK: It's declared as Integer but the `Result` type (and the type it's called as in TorNewIdentity) is a Boolean expression.
Mason Wheeler
+1 for _because I couldn't stop myself_ :D
jachguate
@Mason serves me right for writing it in just a text editor. Thanks!
Frank Shearar
A: 

A small error in previous answer. In function CheckOK Result := Code <> 250; should to be changed to Result := (Code = 250);

PS: Sorry, I see no way to post a comment to the original answer.

Badiboy