rtcsrvmodule.pas

来自「Delphi快速开发Web Server」· PAS 代码 · 共 1,960 行 · 第 1/4 页

PAS
1,960 行
字号
    if assigned(FOnRequestAccepted) then
      FOnRequestAccepted(Sender);

    if assigned(Link) then
      Link.Call_RequestAccepted(Sender);
  except
    on E:Exception do
      with TRtcValue.Create do
        try
          asException:=E.Message;
          if TRtcDataServer(Sender).Request.Info.asBoolean['$XML'] then
            Sender.Write(toXMLrpcResponse)
          else
            Sender.Write(toCode);
        finally
          Free;
        end;
    end;
  end;

procedure TRtcServerModule.Call_ResponseDone(Sender: TRtcConnection);
  begin
  try
    if assigned(FOnResponseDone) then
      FOnResponseDone(Sender);

    if assigned(Link) then
      Link.Call_ResponseDone(Sender);
  except
    on E:Exception do
      with TRtcValue.Create do
        try
          asException:=E.Message;
          if TRtcDataServer(Sender).Request.Info.asBoolean['$XML'] then
            Sender.Write(toXMLrpcResponse)
          else
            Sender.Write(toCode);
        finally
          Free;
        end;
    end;
  end;

procedure TRtcServerModule.Call_Disconnect(Sender: TRtcConnection);
  begin
  try
    if assigned(FOnDisconnect) then
      FOnDisconnect(Sender);

    if assigned(Link) then
      Link.Call_Disconnect(Sender);
  except
    on E:Exception do
      with TRtcValue.Create do
        try
          asException:=E.Message;
          if TRtcDataServer(Sender).Request.Info.asBoolean['$XML'] then
            Sender.Write(toXMLrpcResponse)
          else
            Sender.Write(toCode);
        finally
          Free;
        end;
    end;
  end;

function RandomKey(len:integer):string;
  var
    a:integer;
  begin
  Result:='';
  for a:=1 to len do
    Result:=Result+Char(random(256));
  end;

procedure CryptRead(Crypt:TRtcCryptServer; var Data:string);
  begin
  if assigned(Crypt) and assigned(Crypt.Read) then
    Crypt.Read.DeCrypt(Data);
  end;

procedure CryptWrite(Crypt:TRtcCryptServer; var Data:string);
  begin
  if assigned(Crypt) and assigned(Crypt.Write) then
    Crypt.Write.Crypt(Data);
  end;

procedure TRtcServerModule.Call_DataReceived(Sender: TRtcConnection);
  var
    crypt:TRtcCryptServer;
    tmpcnt:integer;
    code,temp:string;
    output:TRtcHugeString;
    at:integer;
    MyData,MyResult:TRtcValueObject;
    mycall:TRtcDelayedCall;
    FMT:TRtcDataFormat;

  function IsValidControlKey(var Counter:integer; const s:string):boolean;
  {$IFDEF RtcDoNotCheckCryptControlSums}
    begin
    // Old implementation uses 3 - 8 byte control keys,
    // New implementation uses 9 - 14 byte control keys.
    Result:= length(s) in [3..14];
    end;
  {$ELSE}
    var
      i,a,b,Chk:integer;
    begin
    Inc(Counter);
    if Counter>99 then Counter:=1;

    // New implementation sends a counter and a checksum,
    // which can be used to validate the control key.
    if length(s) in [9..14] then
      begin
      b:=(14-length(s))*9+8;
      for i:=5 to length(s) do
        Inc(b, Ord(s[i])-Ord('0'));
      a:=(Ord(s[1])-Ord('0'))*10 +
         (Ord(s[2])-Ord('0'));
      Chk:=(Ord(s[3])-Ord('0'))*10 +
           (Ord(s[4])-Ord('0'));
      Result:= (a=b) and (Chk=Counter);
      end
    else
      Result:=False;
    end;
  {$ENDIF}

  function ExtractControlKey(var Counter:integer):string;
    var
      i,at,len:integer;
    begin
    Result:='';
    at:=0;len:=0;
    { Data will be closed with #13+ControlCode }
    for i:=length(code) downto 1 do
      case code[i] of
        '0'..'9':
          begin
          if len<14 then // we will never use control keys longer than 14 digits
            begin
            Result:=code[i]+Result;
            Inc(len);
            end
          else
            begin
            // Return empty result, which will tell the client to reinitialize encryption
            Result:='';
            Exit;
            end;
          end;
        #13:begin
          at:=i;
          Break;
          end;
        else
          begin
          Result:='';
          Exit;
          end;
        end;

    if at>0 then // number found
      begin
      if not IsValidControlKey(Counter, Result) then
        Result:=''
      else
        SetLength(code,at-1);
      end
    else
      Result:='';
    end;

  function ExtractFinalControlKey(var Counter:integer):string;
    var
      DecompressTo,
      i,at,len:integer;
    begin
    Result:='';len:=0;
    at:=0;
    DecompressTo:=0;
    { Data will be closed with:
      > #13+ControlCode is not compressed
      > #0+ControlCode if compressed. }
    for i:=length(code) downto 1 do
      case code[i] of
        '0'..'9':
          if len<14 then // we will never use control keys longer than 14 digits
            begin
            Result:=code[i]+Result;
            Inc(len);
            end
          else
            begin
            // Return empty result, which will tell the client to reinitialize encryption
            Result:='';
            Exit;
            end;
        #13:
          begin
          at:=i;
          // data is NOT compressed
          Break;
          end;
        #0:
          begin
          at:=i;
          // data is compressed
          DecompressTo:=at-1;
          Break;
          end;
        else
          begin
          Result:='';
          Exit;
          end;
        end;

    if at>0 then // number found
      begin
      if not IsValidControlKey(Counter, Result) then
        Result:=''
      else
        begin
        if DecompressTo>0 then
          begin
          {$IFDEF COMPRESS}
          try
            code:=ZDecompress_Str(code,DecompressTo);
          except
            on E:Exception do
              Result:='';
            end;
          {$ELSE}
            Result:='';
          {$ENDIF}
          end
        else
          SetLength(code,at-1);
        end;
      end
    else
      Result:='';
    end;

  begin
  with TRtcDataServer(Sender) do
    begin
    if Request.Started then
      begin
      if (Request.Query.Text<>'') then
        begin
        if (UpperCase(Request.Query['ACTION'])='HELLO') then
          begin
          // Don't have to handle now
          end
        else if (UpperCase(Request.Query['ACTION'])='START') then
          begin
          // Don't need to handle now
          end
        else if UpperCase(Request.Query['ID'])='NEW' then
          begin
          // Don't need to handle now
          end
        else if (Request.Query['ID']<>'') then
          begin
          // Need to handle now, because there could be a lot of data coming,
          // during which our Session could time out.
          if not FindSession(Request.Query['ID']) then
            if HaveSession(Request.Query['ID']) then
              Response.Status(410,'Session locked')
            else
              Response.Status(410,'Session not found');
          end
        end;
      end;

    if Request.Complete then
      begin
      if (Request.Query.Text<>'') then
        begin
        if (UpperCase(Request.Query['ACTION'])='HELLO') then
          begin
          code:=Read;

          if EncryptionKey=0 then // Encryption not supported
            begin
            // Find Client Session
            if (Request.Query['ID']<>'') and
               (UpperCase(Request.Query['ID'])<>'NEW') then
              begin
              if not FindSession(Request.Query['ID']) then
                begin
                if HaveSession(Request.Query['ID']) then
                  begin
                  Response.Status(410,'Session locked');
                  Write;
                  end
                else
                  begin
                  Response.Status(410,'Session not found');
                  Write;
                  end;
                Exit;
                end
              else
                DelCrypt(Session);
              end
            else if AutoSessions then
              begin
              OpenSession(AutoSessionsLock);
              Session.KeepAlive:=AutoSessionsLive;
              Response.Cookie['ID']:=Session.ID;
              end;
            Write; // send response with empty content
            end
          else if code='' then
            Write
          else
            begin
            // Find Client Session
            if (Request.Query['ID']<>'') and
               (UpperCase(Request.Query['ID'])<>'NEW') then
              begin
              if not FindSession(Request.Query['ID']) then
                begin
                if HaveSession(Request.Query['ID']) then
                  begin
                  Response.Status(410,'Session locked');
                  Write;
                  end
                else
                  begin
                  Response.Status(410,'Session not found');
                  Write;
                  end;
                Exit;
                end
              else
                DelCrypt(Session);
              end;

            if SecureKey<>'' then
              begin
              with TRtcCrypt.Create do
                begin
                Key:=SecureKey;
                DeCrypt(code);
                Free;
                end;
              end;

            tmpcnt:=0;
            temp:=ExtractControlKey(tmpcnt);
            if (code='') or (temp='') then
              begin
              Response.Status(409,'Encryption Key error.');
              Write;
              Exit;
              end;

            if not assigned(Session) then
              begin
              OpenSession(AutoSessionsLock);
              Session.KeepAlive:=AutoSessionsLive;
              Response.Cookie['ID']:=Session.ID;
              end;

            NewCrypt(Session);
            crypt:=GetCrypt(Session);
            crypt.ControlCounter:=tmpcnt;

            crypt.ControlKey:=temp;
            crypt.ClientHello:=code;

            crypt.ServerHello:=RandomKey(EncryptionKey);
            crypt.HaveHello:=True;

            // Encryption object for Write operation
            crypt.Write:=TRtcCrypt.Create;
            crypt.Write.Key:=crypt.ClientHello;

            // Encryption object for Read operation
            crypt.Read:=TRtcCrypt.Create;
            crypt.Read.Key:=crypt.ServerHello;

            // Prepare, encode and send the response
            code:=crypt.ServerHello+crypt.ControlKey;
            CryptWrite(crypt, code);
            Write(code);
            end;
          Exit;
          end
        else if (UpperCase(Request.Query['ACTION'])='START') then
          begin
          if (Request.Query['ID']<>'') and
             (UpperCase(Request.Query['ID'])<>'NEW') then
            begin
            if not FindSession(Request.Query['ID']) then
              begin
              if HaveSession(Request.Query['ID']) then
                begin
                Response.Status(410,'Session locked');
                Write;
                end
              else
                begin
                Response.Status(410,'Session not found');
                Write;
                end;
              Exit;
              end;
            end
          else
            begin
            Response.Status(410,'Session not initialized.');
            Write;
            Exit;
            end;

          code:=Read;

          if EncryptionKey=0 then // Encryption not supported
            Write // send response with empty content
          else if code='' then
            Write
          else
            begin
            crypt:=GetCrypt(Session);

            if crypt=nil then
              begin
              Response.Status(410,'Session not initialized.');
              Write;
              Exit;
              end
            else if not crypt.HaveHello then
              begin
              Response.Status(410,'Session handshake error.');
              Write;
              Exit;
              end;

            // Decode client request
            CryptRead(crypt, code);

            crypt.ControlKey:=ExtractControlKey(crypt.ControlCounter);
            if (crypt.ControlKey='') or (code='') then
              begin
              Response.Status(409,'Encryption Key error.');
              Write;
              Exit;
              end;

            crypt.ClientKey:=code;
            crypt.ServerKey:=RandomKey(EncryptionKey);
            crypt.HaveStart:=True;

            // Set Encryption kexs for Reading and Writing
            crypt.Write.Key:=crypt.ClientKey+crypt.ServerHello;
            crypt.Read.Key :=crypt.ServerKey+crypt.ClientHello;

            // Prepare, encode and send the response
            code:=crypt.ServerKey+crypt.ControlKey;
            CryptWrite(crypt, code);
            Write(code);
            end;
          Exit;
          end
        else if UpperCase(Request.Query['ID'])='NEW' then
          begin
          if ForceEncryption and (EncryptionKey>0) then
            begin
            // 412 = Precondition Failed (Encryption required)
            Response.Status(412,'Encryption required.');
            Write;
            Exit;
            end
          else if AutoSessions then
            begin
            OpenSession(AutoSessionsLock);
            Session.KeepAlive:=AutoSessionsLive;
            Response.Cookie['ID']:=Session.ID;
            end;
          end
        else if (Request.Query['ID']<>'') then
          begin
          // Return empty string if Session expxired or non-existing

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?