summaryrefslogtreecommitdiff
path: root/fpcsrc/packages/fcl-web/src/base/cgiapp.pp
blob: c2a6e182aa35cc4c188639d9e297abb2bf3b5cf0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
{
    This file is part of the Free Pascal run time library.
    Copyright (c) 1999-2000 by the Free Pascal development team

    TCGIApplication class.

    See the file COPYING.FPC, included in this distribution,
    for details about the copyright.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

 **********************************************************************}

{$mode objfpc}
{$H+}

unit cgiapp;

Interface

uses
  CustApp,Classes,SysUtils;

Const
  CGIVarCount = 23 deprecated;

Type
  TCGIVarArray = Array [1..CGIVarCount] of String;

Const
  CgiVarNames : TCGIVarArray =
   ('AUTH_TYPE',
    'CONTENT_LENGTH',
    'CONTENT_TYPE',
    'GATEWAY_INTERFACE',
    'PATH_INFO',
    'PATH_TRANSLATED',
    'QUERY_STRING', 'REMOTE_ADDR',
    'REMOTE_HOST',
    'REMOTE_IDENT',
    'REMOTE_USER',
    'REQUEST_METHOD',
    'SCRIPT_NAME',
    'SERVER_NAME',
    'SERVER_PORT',
    'SERVER_PROTOCOL',
    'SERVER_SOFTWARE',
    'HTTP_ACCEPT',
    'HTTP_ACCEPT_CHARSET',
    'HTTP_ACCEPT_ENCODING',
    'HTTP_IF_MODIFIED_SINCE',
    'HTTP_REFERER',
    'HTTP_USER_AGENT')  deprecated;

Type

  TCgiApplication = Class(TCustomApplication)
  Private
    FResponse : TStream;
    FEmail : String;
    FAdministrator : String;
    FContentTypeEmitted : Boolean;
    FCGIVars : TCGIVarArray;
    FRequestVars,
    FFormFiles : TStrings;
    Function GetCGIVar (Index : Integer) : String;
    Procedure InitCGIVars;
    Procedure InitRequestVars;
    Procedure InitPostVars;
    Procedure InitGetVars;
    Procedure SetContentLength (Value : Integer);
    Procedure SetCGIVar(Index : Integer; Value : String);
    Function GetContentLength : Integer;
    Function GetServerPort : Word;
    Function GetEmail : String;
    Function GetAdministrator : String;
    Procedure ProcessQueryString(Const FQueryString : String);
    Function GetRequestVariable(Const VarName : String) : String;
    Function GetRequestVariableCount : Integer;
    Procedure ProcessURLEncoded(M : TMemoryStream);
    Procedure ProcessMultiPart(M : TMemoryStream; Const Boundary : String);
  Public
    Constructor Create(AOwner : TComponent); override; deprecated;
    Destructor Destroy; override; deprecated;
    Procedure AddResponse(Const S : String); deprecated;
    Procedure AddResponse(Const Fmt : String; Args : Array of const); deprecated;
    Procedure AddResponseLn(Const S : String); deprecated;
    Procedure AddResponseLn(Const Fmt : String; Args : Array of const); deprecated;
    Procedure Initialize; override; deprecated;
    Procedure GetCGIVarList(List : TStrings); deprecated;
    Procedure GetRequestVarList(List : TStrings); deprecated;
    Procedure GetRequestVarList(List : TStrings; NamesOnly : Boolean); deprecated;
    Procedure ShowException(E: Exception);override; deprecated;
    Procedure DeleteFormFiles; deprecated;
    Function EmitContentType : Boolean; deprecated;
    Function GetTempCGIFileName : String; deprecated;
    Function VariableIsUploadedFile(Const VarName : String) : boolean; deprecated;
    Function UploadedFileName(Const VarName : String) : String; deprecated;
    Property AuthType : String Index 1 Read GetCGIVar; deprecated;
    Property ContentLength : Integer Read GetContentLength Write SetContentLength; deprecated; // Index 2
    Property ContentType : String Index 3 Read GetCGIVar Write SetCGIVar; deprecated;
    Property GatewayInterface : String Index 4 Read GetCGIVar; deprecated;
    Property PathInfo : String index 5 read GetCGIvar; deprecated;
    Property PathTranslated : String Index 6 read getCGIVar; deprecated;
    Property QueryString : String Index 7 read getcgivar; deprecated;
    Property RemoteAddress : String Index 8 read GetCGIVar; deprecated;
    Property RemoteHost : String Index 9 read GetCGIVar; deprecated;
    Property RemoteIdent : String Index 10 read GetCGIVar; deprecated;
    Property RemoteUser : String Index 11 read GetCGIVar; deprecated;
    Property RequestMethod : String Index 12 read GetCGIVar; deprecated;
    Property ScriptName : String Index 13 read GetCGIVar; deprecated;
    Property ServerName : String Index 14 read GetCGIVar; deprecated;
    Property ServerPort : Word Read GetServerPort; deprecated; // Index 15
    Property ServerProtocol : String Index 16 read GetCGIVar; deprecated;
    Property ServerSoftware : String Index 17 read GetCGIVar; deprecated;
    Property HTTPAccept : String Index 18 read GetCGIVar; deprecated;
    Property HTTPAcceptCharset : String Index 19 read GetCGIVar; deprecated;
    Property HTTPAcceptEncoding : String Index 20 read GetCGIVar; deprecated;
    Property HTTPIfModifiedSince : String Index 21 read GetCGIVar; deprecated; // Maybe change to TDateTime ??
    Property HTTPReferer : String Index 22 read GetCGIVar; deprecated;
    Property HTTPUserAgent : String Index 23 read GetCGIVar; deprecated;
    Property Email : String Read GetEmail Write FEmail; deprecated;
    Property Administrator : String Read GetAdministrator Write FAdministrator; deprecated;
    Property RequestVariables[VarName : String] : String Read GetRequestVariable; deprecated;
    Property RequestVariableCount : Integer Read GetRequestVariableCount; deprecated;
    Property Response : TStream Read FResponse; deprecated;
  end;

ResourceString
  SWebMaster = 'webmaster' deprecated;
  SCGIError  = 'CGI Error' deprecated;
  SAppEncounteredError = 'The application encountered the following error:' deprecated;
  SError     = 'Error: ' deprecated;
  SNotify    = 'Notify: ' deprecated;
  SErrNoContentLength = 'No content length passed from server!' deprecated;
  SErrUnsupportedContentType = 'Unsupported content type: "%s"' deprecated;
  SErrNoRequestMethod = 'No REQUEST_METHOD passed from server.' deprecated;
  SErrInvalidRequestMethod = 'Invalid REQUEST_METHOD passed from server.' deprecated;

Implementation

uses
  iostream;
  
Type
  TFormFile = Class(TObject)
  Private
    FFileName : String;
  Public  
    Constructor Create(Const AFileName : String);
    Property FileName : String Read FFileName Write FFileName;
  end;  
  
Constructor  TFormFile.Create(Const AFileName : String);

begin
  FFileName:=AFileName;
end;

{$ifdef cgidebug}
Var
  flog : Text;

Procedure Log(Msg : String);

begin
  Writeln(flog,Msg);
end;

Procedure Log(Msg : String;Args : Array of const);

begin
  Writeln(flog,Format(Msg,Args));
end;

Procedure InitLog;

begin
  Assign(flog,'/tmp/cgi.log');
  Rewrite(flog);
  Log('---- Start of log session ---- ');
end;

Procedure DoneLog;

begin
  Close(Flog);
end;
{$endif}

Constructor TCgiApplication.Create(AOwner : TComponent);

begin
  Inherited Create(AOwner);
  FRequestVars:=TStringList.Create;
  FFormFiles:=TStringList.Create;
end;

Destructor TCgiApplication.Destroy;

Var
  i : Integer;

begin
  DeleteFormFiles;
  FFormFiles.Free;
  FRequestVars.Free;
  Inherited;
end;

Function  TCgiApplication.GetCGIVar (Index : Integer) : String;

begin
  Result:=FCGIVars[Index];
end;

Procedure TCgiApplication.InitCGIVars;

Var
  I : Integer;
  L : TStrings;

begin
  L:=TStringList.Create;
  Try
    GetEnvironmentList(L);
    For I:=1 to CGIVarCount do
      FCGIVars[i]:=L.Values[CGIVarNames[i]];
  Finally
    L.Free;
  end;
end;

Function TCgiApplication.GetTempCGIFileName : String;

begin
  Result:=GetTempFileName('/tmp/','CGI')
end;

Procedure TCgiApplication.DeleteFormFiles;

Var
  I,P : Integer;
  FN : String;
  FF : TFormFile;
begin
  For I:=0 to FFormFiles.Count-1 do
    begin
    FF:=TFormFile(FFormFiles.Objects[i]);
    If Assigned(FF) then
      begin
      If FileExists(FF.FileName) then
        DeleteFile(FF.FileName);
      FF.Free;
      end;  
    end;
end;

Procedure TCgiApplication.Initialize;

begin
  StopOnException:=True;
  Inherited;
  InitCGIVars;
  InitRequestVars;
  FResponse:=TIOStream.Create(iosOutput);
end;

Procedure TCgiApplication.GetCGIVarList(List : TStrings);

Var
  I : Integer;

begin
  List.Clear;
  For I:=1 to cgiVarCount do
    List.Add(CGIVarNames[i]+'='+FCGIVars[i]);
end;

Procedure TCgiApplication.GetRequestVarList(List : TStrings);

begin
  GetRequestVarList(List,False);
end;

Procedure TCgiApplication.GetRequestVarList(List : TStrings; NamesOnly : Boolean);

Var
  I,J : Integer;
  S : String;

begin
  List.BeginUpdate;
  Try
    List.Clear;
    // Copy one by one, there may be CR/LF in the variables, causing 'Text' to go wrong.
    If Assigned(FRequestVars) then
      For I:=0 to FRequestVars.Count-1 do
        begin
        S:=FRequestVars[i];
        If NamesOnly then
          begin
          J:=Pos('=',S);
          If (J>0) then
            S:=Copy(S,1,J-1);
          end;
        List.Add(S);
        end;
  finally
    List.EndUpdate;
  end;
end;


Function TCgiApplication.GetContentLength : Integer;

begin
  Result:=StrToIntDef(GetCGIVar(2),-1);
end;

Procedure TCgiApplication.SetContentLength (Value : Integer);

begin
  SetCGIVar(2,IntToStr(Value));
end;

Procedure TCgiApplication.SetCGIVar(Index : Integer; Value : String);

begin
  If Index in [1..cgiVarCount] then
    FCGIVars[Index]:=Value;
end;


Function TCgiApplication.GetServerPort : Word;
begin
  Result:=StrToIntDef(GetCGIVar(15),0);
end;

Function TCgiApplication.EmitContentType : Boolean;

Var
  S: String;

begin
  Result:=Not FContentTypeEmitted;
  If result then
    begin
    S:=ContentType;
    If (S='') then
      S:='text/html';
    AddResponseLn('Content-Type: '+ContentType);
    AddResponseLn('');
    FContentTypeEmitted:=True;
    end;
end;

Procedure TCgiApplication.ShowException(E: Exception);

Var
  TheEmail : String;
  FrameCount: integer;
  Frames: PPointer;
  FrameNumber:Integer;

begin
  If not FContentTypeEmitted then
    begin
    ContentType:='text/html';
    EmitContentType;
    end;
  If (ContentType='text/html') then
    begin
    AddResponseLN('<html><head><title>'+Title+': '+SCGIError+'</title></head>');
    AddResponseLN('<body>');
    AddResponseLN('<center><hr><h1>'+Title+': ERROR</h1><hr></center><br><br>');
    AddResponseLN(SAppEncounteredError+'<br>');
    AddResponseLN('<ul>');
    AddResponseLN('<li>'+SError+' <b>'+E.Message+'</b>');
    AddResponseLn('<li> Stack trace:<br>');
    AddResponseLn(BackTraceStrFunc(ExceptAddr)+'<br>');
    FrameCount:=ExceptFrameCount;
    Frames:=ExceptFrames;
    for FrameNumber := 0 to FrameCount-1 do
      AddResponseLn(BackTraceStrFunc(Frames[FrameNumber])+'<br>');
    AddResponseLn('</ul><hr>');
    TheEmail:=Email;
    If (TheEmail<>'') then
      AddResponseLN('<h5><p><i>'+SNotify+Administrator+': <a href="mailto:'+TheEmail+'">'+TheEmail+'</a></i></p></h5>');
    AddResponseLN('</body></html>');
    end;
end;

Function TCgiApplication.GetEmail : String;

Var
  H : String;

begin
  If (FEmail='') then
    begin
    H:=ServerName;
    If (H<>'') then
      Result:=Administrator+'@'+H
    else
      Result:='';
    end
  else
    Result:=Email;
end;

Function TCgiApplication.GetAdministrator : String;

begin
  If (FADministrator<>'') then
    Result:=FAdministrator
  else
    Result:=SWebMaster;
end;

Procedure TCgiApplication.InitRequestVars;

var
  R : String;

begin
  R:=RequestMethod;
  if (R='') then
    Raise Exception.Create(SErrNoRequestMethod);
  if CompareText(R,'POST')=0 then
    InitPostVars
  else if CompareText(R,'GET')=0 then
    InitGetVars
  else
    Raise Exception.CreateFmt(SErrInvalidRequestMethod,[R]);
end;

Procedure TCgiApplication.ProcessURLEncoded(M : TMemoryStream);


var
  FQueryString : String;

begin
  SetLength(FQueryString,M.Size); // Skip added Null.
  M.Read(FQueryString[1],M.Size);
  ProcessQueryString(FQueryString);
end;

Type
  TFormItem = Class(TObject)
    DisPosition : String;
    Name : String;
    isFile : Boolean;
    FileName : String;
    ContentType : String;
    DLen : Integer;
    Data : String;
    Procedure Process;
  end;

Procedure TFormItem.Process;

  Function GetLine(Var S : String) : String;

  Var
    P : Integer;

  begin
    P:=Pos(#13#10,S);
    If (P<>0) then
      begin
      Result:=Copy(S,1,P-1);
      Delete(S,1,P+1);
      end;
  end;

  Function GetWord(Var S : String) : String;

  Var
    I,len : Integer;
    Quoted : Boolean;
    C : Char;

  begin
    len:=length(S);
    quoted:=false;
    Result:='';
    for i:=1 to len do
      Begin
      c:=S[i];
      if (c='"') then
        Quoted:=Not Quoted
      else
        begin
        if not (c in [' ','=',';',':']) or Quoted then
          Result:=Result+C;
        if (c in [';',':','=']) and (not quoted) then
          begin
          Delete(S,1,I);
          Exit;
          end;
        end;
      end;
     S:='';
  end;

Var
  Line : String;
  Words : TStringList;
  i,len : integer;
  c : char;
  S : string;
  quoted : boolean;

begin
  Line:=GetLine(Data);
  While (Line<>'') do
    begin
    S:=GetWord(Line);
    While (S<>'') do
      begin
      If CompareText(S,'Content-Disposition')=0 then
        Disposition:=GetWord(Line)
      else if CompareText(S,'name')=0 Then
        Name:=GetWord(Line)
      else if CompareText(S,'filename')=0 then
        begin
        FileName:=GetWord(Line);
        isFile:=True;
        end
      else if CompareText(S,'Content-Type')=0 then
        ContentType:=GetWord(Line);
      S:=GetWord(Line);
      end;
    Line:=GetLine(Data);
    end;
  // Now Data contains the rest of the data, plus a CR/LF. Strip the CR/LF
  Len:=Length(Data);
  If (len>2) then
    Data:=Copy(Data,1,Len-2);
end;

Function MakeString(PStart,PEnd : Pchar) : String;

begin
  SetLength(Result,PEnd-PStart);
  If Length(Result)>0 then
    Move(PStart^,Result[1],Length(Result));
end;

procedure FormSplit(var Cnt : String; boundary: String; List : TList);

// Splits the form into items
var
  Sep : string;
  Clen,slen, p:longint;
  FI : TFormItem;

begin
  Sep:='--'+boundary+#13+#10;
  Slen:=length(Sep);
  CLen:=Pos('--'+Boundary+'--',Cnt);
  // Cut last marker
  Cnt:=Copy(Cnt,1,Clen-1);
  // Cut first marker
  Delete(Cnt,1,Slen);
  Clen:=Length(Cnt);
  While Clen>0 do
    begin
    Fi:=TFormItem.Create;
    List.Add(Fi);
    P:=pos(Sep,Cnt);
    If (P=0) then
      P:=CLen+1;
    FI.Data:=Copy(Cnt,1,P-1);
    delete(Cnt,1,P+SLen-1);
    CLen:=Length(Cnt);
    end;
end;

function GetNextLine(Var Data: String):string;

Var
  p : Integer;

begin
  P:=Pos(#13#10,Data);
  If (P<>0) then
    begin
    Result:=Copy(Data,1,P-1);
    Delete(Data,1,P+1);
    end;
end;

Procedure TCgiApplication.ProcessMultiPart(M : TMemoryStream; Const Boundary : String);

Var
  L : TList;
  B : String;
  I,Index : Integer;
  S,FF,key, Value : String;
  FI : TFormItem;
  F : TStream;

begin
  i:=Pos('=',Boundary);
  B:=Copy(Boundary,I+1,Length(Boundary)-I);
  I:=Length(B);
  If (I>0) and (B[1]='"') then
    B:=Copy(B,2,I-2);
  L:=TList.Create;
  Try
    SetLength(S,M.Size);
    If Length(S)>0 then
      Move(M.Memory^,S[1],M.Size);
    FormSplit(S,B,L);
    For I:=L.Count-1 downto 0 do
      begin
      FI:=TFormItem(L[i]);
      FI.Process;
      If (FI.Name='') then
        Raise Exception.CreateFmt('Invalid multipart encoding: %s',[FI.Data]);
      Key:=FI.Name;
      If Not FI.IsFile Then
        begin
        Value:=FI.Data
        end
      else
        begin
        Value:=FI.FileName;
        FF:=GetTempCGIFileName;
        FFormFiles.AddObject(Key,TFormFile.Create(FF));
        F:=TFileStream.Create(FF,fmCreate);
        Try
          if Length(FI.Data)>0 then
            F.Write(FI.Data[1],Length(FI.Data));
        finally
          F.Free;
        end;
        FI.Free;
        L[i]:=Nil;
        end;
      FRequestVars.Add(Key+'='+Value)
      end;
  Finally
    For I:=0 to L.Count-1 do
      TObject(L[i]).Free;
    L.Free;
  end;
end;

Type
  TCapacityStream = Class(TMemoryStream)
  Public
    Property Capacity;
  end;

Procedure TCgiApplication.InitPostVars;

Var
  M  : TCapacityStream;
  I  : TIOStream;
  Cl : Integer;
  B  : Byte;

begin
  CL:=ContentLength;
  M:=TCapacityStream.Create;
  Try
    I:=TIOStream.Create(iosInput);
    Try
      if (CL<>0) then
        begin
        M.Capacity:=(Cl);
        M.CopyFrom(I,Cl);
        end
      else
        begin
        B:=0;
        While (I.Read(B,1)>0) do
          M.Write(B,1)
        end;
    Finally
      I.Free;
    end;
    if CompareText(ContentType,'MULTIPART/FORM-DATA')=0 then
      ProcessMultiPart(M,ContentType)
    else if CompareText(ContentType,'APPLICATION/X-WWW-FORM-URLENCODED')=0 then
      ProcessUrlEncoded(M)
    else
      Raise Exception.CreateFmt(SErrUnsupportedContentType,[ContentType]);
  finally
    M.Free;
  end;
end;

Procedure TCgiApplication.InitGetVars;

Var
  FQueryString : String;

begin
  FQueryString:=QueryString;
  If (FQueryString<>'') then
    ProcessQueryString(FQueryString);
end;

const
   hexTable = '0123456789ABCDEF';

Procedure TCgiApplication.ProcessQueryString(Const FQueryString : String);


var
  queryItem : String;
  delimiter : Char;
  aString : String;
  aSepStr : String;
  aPos    : Integer;
  aLenStr : Integer;
  aLenSep : Integer;

  function hexConverter(h1, h2 : Char) : Char;

  var
    B : Byte;

  begin
    B:=(Pos(upcase(h1),hexTable)-1)*16;
    B:=B+Pos(upcase(h2),hexTable)-1;
    Result:=chr(B);
  end;

  procedure Convert_ESC_Chars;

  var
    index : Integer;

  begin
    Index:=Length(QueryItem);
    While (Index>0) do
      begin
      If QueryItem[Index]='+' then
        QueryItem[Index]:=' '
      else If (QueryItem[Index]='%') and (Index<Length(QueryItem)-1) then
        begin
        QueryItem[Index]:=hexConverter(QueryItem[Index+1],QueryItem[index+2]);
        System.Delete(QueryItem,Index+1,2);
        end;
      dec(Index);
      end;
  end;

  procedure InitToken(aStr, aSep : String);

  begin
    aString := aStr;
    aSepStr := aSep;
    aPos    := 1;
    aLenStr := Length(aString);
    aLenSep := Length(aSepStr);
  end;

  function NextToken(var aToken : String; out aSepChar : Char) : Boolean;

  var
    i : Integer;
    j : Integer;
    BoT : Integer;
    EoT : Integer;
    isSep : Boolean;

  begin
    BoT:=aPos;
    EoT:=aPos;
    for i:=aPos to aLenStr do
      begin
      IsSep := false;
      for j := 1 to aLenSep do
        begin
        if aString[i] = aSepStr[j] then
          begin
          IsSep := true;
          Break;
          end;
        end;
      if IsSep then
        begin
        EoT  := i;
        aPos := i + 1;
        aSepChar := aString[i];
        Break;
        end
      else
        begin
        if i = aLenStr then
          begin
          EoT  := i;
          aPos := i;
          Break;
          end;
        end;
      end;
    if aPos < aLenStr then
      begin
      aToken := Copy(aString, BoT, EoT - BoT);
      Result := true;
      end
    else
      begin
      if aPos = aLenStr then
        begin
        aToken := Copy(aString, BoT, EoT - BoT + 1);
        Result := true;
        aPos   := aPos + 1;
        end
      else
        begin
        Result := false;
       end;
    end;
  end;


begin
   InitToken(FQueryString, '&');
   while NextToken(QueryItem, delimiter) do
     begin
     if (QueryItem<>'') then
       begin
       Convert_ESC_Chars;
       FRequestVars.Add(QueryItem);
       end;
     end;
end;

Function TCGIApplication.GetRequestVariable(Const VarName : String) : String;

begin
 If Assigned(FRequestVars) then
   Result:=FRequestVars.Values[VarName];
end;

Function TCGIApplication.GetRequestVariableCount : Integer;

begin
  If Assigned(FRequestVars) then
    Result:=FRequestVars.Count
  else
    Result:=0;
end;

Procedure TCGIApplication.AddResponse(Const S : String);

Var
  L : Integer;

begin
  L:=Length(S);
  If L>0 then
    FResponse.Write(S[1],L);
end;

Procedure TCGIApplication.AddResponse(Const Fmt : String; Args : Array of const);

begin
  AddResponse(Format(Fmt,Args));
end;

Procedure TCGIApplication.AddResponseLN(Const S : String);


begin
  AddResponse(S+LineEnding);
end;

Procedure TCGIApplication.AddResponseLN(Const Fmt : String; Args : Array of const);

begin
  AddResponseLN(Format(Fmt,Args));
end;

Function TCGIApplication.VariableIsUploadedFile(Const VarName : String) : boolean;

begin
  Result:=FFormFiles.IndexOf(VarName)<>-1;
end;

Function TCGIApplication.UploadedFileName(Const VarName : String) : String;

Var
  FF : TFormFile;
  i : Integer;
 
begin
  Result:='';
  I:=FFormFiles.IndexOf(VarName);
  If (I<>-1) then
    begin
    FF:=TFormFile(FFormFiles.Objects[i]);
    If Assigned(FF) then
      Result:=FF.FileName;
    end;  
end;

{$ifdef cgidebug}
Initialization
  initLog;

Finalization
  DoneLog;
{$endif}
end.