summaryrefslogtreecommitdiff
path: root/fpcsrc/utils/fppkg/lnet/lfastcgi.pp
blob: 0076d0f59eef93d0201e02e499b5ef22cecab599 (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
{ FastCGI requester support for lNet

  Copyright (C) 2006-2008 Micha Nelissen

  This library is Free software; you can redistribute it and/or modify it
  under the terms of the GNU Library General Public License as published by
  the Free Software Foundation; either version 2 of the License, or (at your
  option) any later version.

  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. See the GNU Library General Public License
  for more details.

  You should have received a Copy of the GNU Library General Public License
  along with This library; if not, Write to the Free Software Foundation,
  Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  
  This license has been modified. See file LICENSE.ADDON for more information.
  Should you find these sources without a LICENSE File, please contact
  me at ales@chello.sk
}

unit lfastcgi;

{$mode objfpc}{$h+}

interface

uses
  classes, sysutils, fastcgi_base, lnet, levents, lstrbuffer, ltimer;

type
  TLFastCGIClient = class;
  TLFastCGIRequest = class;
  TLFastCGIPool = class;

  TLFastCGIRequestEvent = procedure(ARequest: TLFastCGIRequest) of object;

  PLFastCGIRequest = ^TLFastCGIRequest;
  TLFastCGIRequest = class(TObject)
  protected
    FID: integer;
    FClient: TLFastCGIClient;
    FBuffer: TStringBuffer;
    FBufferSendPos: integer;
    FHeader: FCGI_Header;
    FHeaderPos: integer;
    FContentLength: integer;
    FInputBuffer: pchar;
    FInputSize: integer;
    FOutputDone: boolean;
    FStderrDone: boolean;
    FOutputPending: boolean;
    FNextFree: TLFastCGIRequest;
    FNextSend: TLFastCGIRequest;
    FOnEndRequest: TLFastCGIRequestEvent;
    FOnInput: TLFastCGIRequestEvent;
    FOnOutput: TLFastCGIRequestEvent;
    FOnStderr: TLFastCGIRequestEvent;

    procedure HandleReceive;
    procedure HandleReceiveEnd;
    function  HandleSend: boolean;
    procedure DoEndRequest;
    procedure DoOutput;
    procedure DoStderr;
    procedure EndRequest;
    procedure RewindBuffer;
    procedure SetContentLength(NewLength: integer);
    procedure SendEmptyRec(AType: integer);
    procedure SendGetValues;
    procedure SetID(const NewID: integer);
  public
    constructor Create;
    destructor Destroy; override;
    
    procedure AbortRequest;
    function  Get(ABuffer: pchar; ASize: integer): integer;
    procedure ParseClientBuffer;
    function  SendBuffer: integer;
    function  SendPrivateBuffer: boolean;
    procedure SendBeginRequest(AType: integer);
    procedure SendParam(const AName, AValue: string; AReqType: integer = FCGI_PARAMS);
    function  SendInput(const ABuffer: pchar; ASize: integer): integer;
    procedure DoneParams;
    procedure DoneInput;

    property ID: integer read FID write SetID;
    property StderrDone: boolean read FStderrDone;
    property OutputDone: boolean read FOutputDone;
    property OutputPending: boolean read FOutputPending;
    property OnEndRequest: TLFastCGIRequestEvent read FOnEndRequest write FOnEndRequest;
    property OnInput: TLFastCGIRequestEvent read FOnInput write FOnInput;
    property OnOutput: TLFastCGIRequestEvent read FOnOutput write FOnOutput;
    property OnStderr: TLFastCGIRequestEvent read FOnStderr write FOnStderr;
  end;

  TFastCGIClientState = (fsIdle, fsConnecting, fsConnectingAgain, 
    fsStartingServer, fsHeader, fsData, fsFlush);
  
  PLFastCGIClient = ^TLFastCGIClient;
  TLFastCGIClient = class(TLTcp)
  protected
    FRequests: PLFastCGIRequest;
    FRequestsCount: integer;
    FNextRequestID: integer;
    FRequestsSent: integer;
    FFreeRequest: TLFastCGIRequest;
    FSendRequest: TLFastCGIRequest;
    FRequest: TLFastCGIRequest;
    FState: TFastCGIClientState;
    FNextFree: TLFastCGIClient;
    FPool: TLFastCGIPool;
    FBuffer: pchar;
    FBufferEnd: pchar;
    FBufferPos: pchar;
    FBufferSize: dword;
    FReqType: byte;
    FContentLength: integer;
    FPaddingLength: integer;

    function Connect: Boolean; override;
    procedure ConnectEvent(ASocket: TLHandle); override;
    procedure DisconnectEvent(ASocket: TLHandle); override;
    procedure ErrorEvent(ASocket: TLHandle; const msg: string); override;
    function  CreateRequester: TLFastCGIRequest;
    procedure HandleGetValuesResult;
    procedure HandleReceive(ASocket: TLSocket);
    procedure HandleSend(ASocket: TLSocket);
    procedure ParseBuffer;
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;

    procedure AddToSendQueue(ARequest: TLFastCGIRequest);
    function  BeginRequest(AType: integer): TLFastCGIRequest;
    procedure EndRequest(ARequest: TLFastCGIRequest);
    procedure Flush;
    function  GetBuffer(ABuffer: pchar; ASize: integer): integer;

    property ReqType: byte read FReqType;
    property RequestsSent: integer read FRequestsSent;
  end;

  TSpawnState = (ssNone, ssSpawning, ssSpawned);

  TLFastCGIPool = class(TObject)
  protected
    FClients: PLFastCGIClient;
    FClientsCount: integer;
    FClientsAvail: integer;
    FClientsMax: integer;
    FMaxRequestsConn: integer;
    FFreeClient: TLFastCGIClient;
    FTimer: TLTimer;
    FEventer: TLEventer;
    FAppName: string;
    FAppEnv: string;
    FHost: string;
    FPort: integer;
    FSpawnState: TSpawnState;
    
    procedure AddToFreeClients(AClient: TLFastCGIClient);
    function  CreateClient: TLFastCGIClient;
    procedure ConnectClients(Sender: TObject);
    procedure StartServer;
  public
    constructor Create;
    destructor Destroy; override;

    function  BeginRequest(AType: integer): TLFastCGIRequest;
    procedure EndRequest(AClient: TLFastCGIClient);

    property AppEnv: string read FAppEnv write FAppEnv;
    property AppName: string read FAppName write FAppName;
    property ClientsMax: integer read FClientsMax write FClientsMax;
    property Eventer: TLEventer read FEventer write FEventer;
    property MaxRequestsConn: integer read FMaxRequestsConn write FMaxRequestsConn;
    property Host: string read FHost write FHost;
    property Port: integer read FPort write FPort;
    property Timer: TLTimer read FTimer;
  end;

implementation

uses
  lSpawnFCGI;

{ TLFastCGIRequest }

constructor TLFastCGIRequest.Create;
begin
  inherited;

  FBuffer := InitStringBuffer(504);
  FHeader.Version := FCGI_VERSION_1;
  FHeaderPos := -1;
end;

destructor TLFastCGIRequest.Destroy;
begin
  inherited;
  FreeMem(FBuffer.Memory);
end;

procedure TLFastCGIRequest.HandleReceive;
begin
  case FClient.ReqType of
    FCGI_STDOUT: DoOutput;
    FCGI_STDERR: DoStderr;
    FCGI_END_REQUEST: EndRequest;
    FCGI_GET_VALUES_RESULT: FClient.HandleGetValuesResult;
  else
    FClient.Flush;
  end;
end;

procedure TLFastCGIRequest.HandleReceiveEnd;
begin
  case FClient.ReqType of
    FCGI_STDOUT: FOutputDone := true;
    FCGI_STDERR: FStderrDone := true;
  end;
end;

function TLFastCGIRequest.HandleSend: boolean;
begin
  if FOnInput <> nil then
    FOnInput(Self);
  Result := FInputBuffer = nil;
end;

procedure TLFastCGIRequest.DoOutput;
begin
  if FOnOutput <> nil then
    FOnOutput(Self);
end;

procedure TLFastCGIRequest.DoStderr;
begin
  if FOnStderr <> nil then
    FOnStderr(Self);
end;

procedure TLFastCGIRequest.DoEndRequest;
begin
  if FOnEndRequest <> nil then
    FOnEndRequest(Self);
end;

procedure TLFastCGIRequest.EndRequest;
begin
  FOutputDone := false;
  FStderrDone := false;
  FClient.EndRequest(Self);
  FClient.Flush;
  RewindBuffer;
  DoEndRequest;
end;

function TLFastCGIRequest.Get(ABuffer: pchar; ASize: integer): integer;
begin
  Result := FClient.GetBuffer(ABuffer, ASize);
end;

procedure TLFastCGIRequest.ParseClientBuffer;
begin
  FOutputPending := false;
  if (FClient.Iterator <> nil) and FClient.Iterator.IgnoreRead then
    FClient.HandleReceive(nil)
  else
    FClient.ParseBuffer;
end;

procedure TLFastCGIRequest.SetID(const NewID: integer);
begin
  FID := NewID;
  FHeader.RequestIDB0 := byte(NewID and $FF);
  FHeader.RequestIDB1 := byte((NewID shr 8) and $FF);
end;

procedure TLFastCGIRequest.SetContentLength(NewLength: integer);
begin
  FContentLength := NewLength;
  FHeader.ContentLengthB0 := byte(NewLength and $FF);
  FHeader.ContentLengthB1 := byte((NewLength shr 8) and $FF);
  FHeader.PaddingLength := byte(7-((NewLength+7) and 7));
end;

const
  PaddingBuffer: array[0..7] of char = (#0, #0, #0, #0, #0, #0, #0, #0);
type
  TLFastCGIStringSize = record
    Size: integer;
    SizeBuf: array[0..3] of char;
  end;

function GetFastCGIStringSize(ABufferPos: pbyte; var ASize: integer): integer;
begin
  ASize := ABufferPos[0];
  if ASize >= 128 then
  begin
    ASize := ((ABufferPos[0] shl 24) and $7f) or (ABufferPos[1] shl 16)
      or (ABufferPos[2] shl 8) or ABufferPos[3];
    Result := 4;
  end else
    Result := 1;
end;
  
procedure FillFastCGIStringSize(const AStr: string; var AFastCGIStr: TLFastCGIStringSize);
var
  lLen: dword;
begin
  lLen := dword(Length(AStr));
  if lLen > 127 then
  begin
    AFastCGIStr.Size := 4;
    AFastCGIStr.SizeBuf[0] := char($80 + ((lLen shr 24) and $ff));
    AFastCGIStr.SizeBuf[1] := char((lLen shr 16) and $ff);
    AFastCGIStr.SizeBuf[2] := char((lLen shr 8) and $ff);
    AFastCGIStr.SizeBuf[3] := char(lLen and $ff);
  end else begin
    AFastCGIStr.Size := 1;
    AFastCGIStr.SizeBuf[0] := char(lLen);
  end;
end;

procedure TLFastCGIRequest.SendBeginRequest(AType: integer);
var
  lBody: FCGI_BeginRequestBody;
begin
  lBody.roleB1 := byte((AType shr 8) and $ff);
  lBody.roleB0 := byte(AType and $ff);
  lBody.flags := FCGI_KEEP_CONN;
  FHeader.ReqType := FCGI_BEGIN_REQUEST;
  SetContentLength(sizeof(lBody));
  AppendString(FBuffer, @FHeader, sizeof(FHeader));
  AppendString(FBuffer, @lBody, sizeof(lBody));
end;

procedure TLFastCGIRequest.SendParam(const AName, AValue: string; AReqType: integer = FCGI_PARAMS);
var
  lNameLen: TLFastCGIStringSize;
  lValueLen: TLFastCGIStringSize;
  lTotalLen: integer;
begin
  FillFastCGIStringSize(AName, lNameLen);
  FillFastCGIStringSize(AValue, lValueLen);
  lTotalLen := lNameLen.Size+lValueLen.Size+Length(AName)+Length(AValue);
  if (FHeader.ReqType = AReqType) and (FBufferSendPos = 0) 
    and (0 <= FHeaderPos) and (FHeaderPos < FBuffer.Pos - FBuffer.Memory) then
  begin
    { undo padding }
    Dec(FBuffer.Pos, FHeader.PaddingLength);
    SetContentLength(FContentLength+lTotalLen);
    Move(FHeader, FBuffer.Memory[FHeaderPos], sizeof(FHeader));
  end else begin
    FHeader.ReqType := AReqType;
    SetContentLength(lTotalLen);
    FHeaderPos := FBuffer.Pos - FBuffer.Memory;
    AppendString(FBuffer, @FHeader, sizeof(FHeader));
  end;
  AppendString(FBuffer, @lNameLen.SizeBuf[0], lNameLen.Size);
  AppendString(FBuffer, @lValueLen.SizeBuf[0], lValueLen.Size);
  AppendString(FBuffer, AName);
  AppendString(FBuffer, AValue);
  AppendString(FBuffer, @PaddingBuffer[0], FHeader.PaddingLength);
end;

procedure TLFastCGIRequest.SendGetValues;
var
  lRequestID: integer;
begin
  { management record type has request id 0 }
  lRequestID := ID;
  ID := 0;
  SendParam('FCGI_MAX_REQS', '', FCGI_GET_VALUES);
  { if we're the first connection, ask max. # connections }
  if FClient.FPool.FClientsAvail = 1 then
    SendParam('FCGI_MAX_CONNS', '', FCGI_GET_VALUES);
  ID := lRequestID;
end;

function  TLFastCGIRequest.SendInput(const ABuffer: pchar; ASize: integer): integer;
begin
  { first send current buffer if any }
  if FInputBuffer <> nil then
  begin
    Result := SendBuffer;
    if FInputBuffer <> nil then exit;
  end else Result := 0;
  if Result >= ASize then exit;
  if FInputBuffer = nil then
  begin
    FInputBuffer := ABuffer+Result;
    FInputSize := ASize-Result;
    FHeader.ReqType := FCGI_STDIN;
    SetContentLength(FInputSize);
    AppendString(FBuffer, @FHeader, sizeof(FHeader));
  end;
  Inc(Result, SendBuffer);
end;

procedure TLFastCGIRequest.RewindBuffer;
begin
  FBufferSendPos := 0;
  FHeaderPos := -1;
  { rewind stringbuffer }
  FBuffer.Pos := FBuffer.Memory;
end;

function TLFastCGIRequest.SendPrivateBuffer: boolean;
var
  lWritten: integer;
begin
  { nothing to send ? }
  if FBuffer.Pos-FBuffer.Memory = FBufferSendPos then
    exit(true);
  { already a queue and we are not first in line ? no use in trying to send then }
  if (FClient.FSendRequest = nil) or (FClient.FSendRequest = Self) then
  begin
    lWritten := FClient.Send(FBuffer.Memory[FBufferSendPos], 
      FBuffer.Pos-FBuffer.Memory-FBufferSendPos);
    Inc(FBufferSendPos, lWritten);
    Result := FBufferSendPos = FBuffer.Pos-FBuffer.Memory;
    { do not rewind buffer, unless remote side has had chance to disconnect }
    if Result then
      RewindBuffer;
  end else
    Result := false;
  if not Result then
    FClient.AddToSendQueue(Self);
end;

function TLFastCGIRequest.SendBuffer: integer;
var
  lWritten: integer;
begin
  { already a queue and we are not first in line ? no use in trying to send then }
  if (FClient.FSendRequest <> nil) and (FClient.FSendRequest <> Self) then 
    exit(0);

  { header to be sent? }
  if not SendPrivateBuffer then exit(0);
  { first write request header, then wait for possible disconnect }
  if FBufferSendPos > 0 then exit(0);
  if FInputBuffer = nil then exit(0);

  lWritten := FClient.Send(FInputBuffer^, FInputSize);
  Inc(FInputBuffer, lWritten);
  Dec(FInputSize, lWritten);
  if FInputSize = 0 then
  begin
    FInputBuffer := nil;
    AppendString(FBuffer, @PaddingBuffer[0], FHeader.PaddingLength);
  end else
    FClient.AddToSendQueue(Self);
  Result := lWritten;
end;

procedure TLFastCGIRequest.SendEmptyRec(AType: integer);
begin
  FHeader.ReqType := AType;
  SetContentLength(0);
  AppendString(FBuffer, @FHeader, sizeof(FHeader));
  { no padding needed for empty string }
end;

procedure TLFastCGIRequest.DoneParams;
begin
  SendEmptyRec(FCGI_PARAMS);
end;

procedure TLFastCGIRequest.DoneInput;
begin
  SendEmptyRec(FCGI_STDIN);
  SendPrivateBuffer;
end;

procedure TLFastCGIRequest.AbortRequest;
begin
  FHeader.ReqType := FCGI_ABORT_REQUEST;
  SetContentLength(0);
  AppendString(FBuffer, @FHeader, sizeof(FHeader));
  SendPrivateBuffer;
end;

{ TLFastCGIClient }

const
  DataBufferSize = 64*1024-1;

constructor TLFastCGIClient.Create(AOwner: TComponent);
begin
  inherited;

  FBuffer := GetMem(DataBufferSize+1);
  FBufferPos := FBuffer;
  FBufferEnd := FBuffer;
  FRequests := AllocMem(sizeof(TLFastCGIRequest));
  FRequestsCount := 1;
  FFreeRequest := nil;
  OnReceive := @HandleReceive;
  OnCanSend := @HandleSend;
end;

destructor TLFastCGIClient.Destroy;
var
  I: integer;
begin
  for I := 0 to FNextRequestID-1 do
    FRequests[I].Free;
  FreeMem(FRequests);
  FreeMem(FBuffer);
  inherited;
end;

function TLFastCGIClient.GetBuffer(ABuffer: pchar; ASize: integer): integer;
begin
  Result := FBufferEnd - FBufferPos;
  if Result > FContentLength then 
    Result := FContentLength;
  if Result > ASize then
    Result := ASize;
  Move(FBufferPos^, ABuffer^, Result);
  Inc(FBufferPos, Result);
  Dec(FContentLength, Result);
  { buffer empty? reset }
  if FBufferPos = FBufferEnd then
  begin
    FBufferPos := FBuffer;
    FBufferEnd := FBuffer;
  end;
end;

procedure TLFastCGIClient.ConnectEvent(ASocket: TLHandle);
begin
  if FState = fsStartingServer then
    FPool.FSpawnState := ssSpawned;
  FState := fsHeader;
  if FPool <> nil then
    FPool.AddToFreeClients(Self);

  inherited;
end;

procedure TLFastCGIClient.DisconnectEvent(ASocket: TLHandle);
var
  I: integer;
  needReconnect: boolean;
begin
  inherited;
  FRequestsSent := 0;
  needReconnect := false;
  for I := 0 to FNextRequestID-1 do
    if FRequests[I].FNextFree = nil then
    begin
      { see if buffer contains request, then assume we can resend that }
      if FRequests[I].FBufferSendPos > 0 then
      begin
        needReconnect := true;
        FRequests[I].FBufferSendPos := 0;
        FRequests[I].SendPrivateBuffer;
      end else
      if FRequests[I].FBuffer.Memory = FRequests[I].FBuffer.Pos then
        needReconnect := true
      else
        FRequests[I].EndRequest;
    end;
  if needReconnect then 
    Connect;
end;

procedure TLFastCGIClient.ErrorEvent(ASocket: TLHandle; const msg: string);
begin
  if (FState = fsConnectingAgain) 
    or ((FState = fsConnecting) and (FPool.FSpawnState = ssSpawned)) then
  begin
    FRequest.DoEndRequest;
    EndRequest(FRequest);
    FState := fsIdle;
  end else
  if FState = fsConnecting then
  begin
    FPool.StartServer;
    FState := fsStartingServer;
  end;
end;

procedure TLFastCGIClient.HandleGetValuesResult;
var
  lNameLen, lValueLen, lIntVal, lCode: integer;
  lBufferPtr: pchar;
  lPrevChar: char;

  procedure GetIntVal;
  begin
    lPrevChar := lBufferPtr[lNameLen+lValueLen];
    lBufferPtr[lNameLen+lValueLen] := #0;
    Val(lBufferPtr+lNameLen, lIntVal, lCode);
    lBufferPtr[lNameLen+lValueLen] := lPrevChar;
  end;

begin
  repeat
    lBufferPtr := FBufferPos;
    Inc(lBufferPtr, GetFastCGIStringSize(PByte(lBufferPtr), lNameLen));
    Inc(lBufferPtr, GetFastCGIStringSize(PByte(lBufferPtr), lValueLen));
    if lBufferPtr + lNameLen + lValueLen > FBufferEnd then exit;
    if StrLComp(lBufferPtr, 'FCGI_MAX_REQS', lNameLen) = 0 then
    begin
      GetIntVal;
      if (lCode = 0) and (FRequestsCount <> lIntVal) then
      begin
        FRequestsCount := lIntVal;
        ReallocMem(FRequests, sizeof(TLFastCGIRequest)*lIntVal);
      end;
    end else
    if StrLComp(lBufferPtr, 'FCGI_MAX_CONNS', lNameLen) = 0 then
    begin
      GetIntVal;
      if lCode = 0 then
        FPool.ClientsMax := lIntVal;
    end;
    Inc(lBufferPtr, lNameLen+lValueLen);
    Dec(FContentLength, lBufferPtr-FBufferPos);
    FBufferPos := lBufferPtr;
  until FContentLength = 0;
end;

procedure TLFastCGIClient.HandleReceive(ASocket: TLSocket);
var
  lRead: integer;
begin
  lRead := Get(FBufferEnd^, DataBufferSize-PtrUInt(FBufferEnd-FBuffer));
  if lRead = 0 then exit;
  { remote side has had chance to disconnect, clear buffer }
  Inc(FBufferEnd, lRead);
  ParseBuffer;
end;

procedure TLFastCGIClient.HandleSend(ASocket: TLSocket);
var
  lRequest: TLFastCGIRequest;
begin
  if FSendRequest = nil then exit;
  lRequest := FSendRequest.FNextSend;
  repeat
    if not lRequest.SendPrivateBuffer or not lRequest.HandleSend then
      exit;

    lRequest.FNextSend := nil;
    { only this one left in list ? }
    if FSendRequest = lRequest then
    begin
      FSendRequest := nil;
      exit;
    end else begin
      lRequest := lRequest.FNextSend;
      FSendRequest.FNextSend := lRequest;
    end;
  until false;
end;

procedure TLFastCGIClient.AddToSendQueue(ARequest: TLFastCGIRequest);
begin
  if ARequest.FNextSend <> nil then exit;

  if FSendRequest = nil then
    FSendRequest := ARequest
  else
    ARequest.FNextSend := FSendRequest.FNextSend;
  FSendRequest.FNextSend := ARequest;
end;

procedure TLFastCGIClient.ParseBuffer;
var
  lHeader: PFCGI_Header;
  lReqIndex: integer;
begin
  repeat
    case FState of
      fsHeader:
      begin
        if FBufferEnd-FBufferPos < sizeof(FCGI_Header) then
          exit;
        lHeader := PFCGI_Header(FBufferPos);
        FReqType := lHeader^.ReqType;
        lReqIndex := (lHeader^.RequestIDB1 shl 8) or lHeader^.RequestIDB0;
        FContentLength := (lHeader^.ContentLengthB1 shl 8) or lHeader^.ContentLengthB0;
        FPaddingLength := lHeader^.PaddingLength;
        Inc(FBufferPos, sizeof(lHeader^));
        if lReqIndex > 0 then
          Dec(lReqIndex);
        if (lReqIndex < FRequestsCount) and (FRequests[lReqIndex] <> nil) then
        begin
          FRequest := FRequests[lReqIndex];
          if FContentLength > 0 then
            FState := fsData
          else begin
            FRequest.HandleReceiveEnd;
            Flush;
          end;
        end else
          Flush;
      end;
      fsData: 
      begin
        FRequest.HandleReceive;
        if FContentLength = 0 then 
          Flush
        else begin
          FRequest.FOutputPending := true;
          exit;
        end;
      end;
      fsFlush: Flush;
    end;
  until FBufferPos = FBufferEnd;
end;

procedure TLFastCGIClient.Flush;

  function FlushSize(var ANumBytes: integer): boolean;
  var
    lFlushBytes: integer;
  begin
    lFlushBytes := ANumBytes;
    if lFlushBytes > FBufferEnd - FBufferPos then
      lFlushBytes := FBufferEnd - FBufferPos;
    Dec(ANumBytes, lFlushBytes);
    Inc(FBufferPos, lFlushBytes);
    Result := ANumBytes = 0;
  end;

begin
  FState := fsFlush;
  if FlushSize(FContentLength) and FlushSize(FPaddingLength) then
  begin
    { buffer empty? reset }
    if FBufferPos = FBufferEnd then
    begin
      FBufferPos := FBuffer;
      FBufferEnd := FBuffer;
    end;
    FState := fsHeader;
    FRequest := nil;
  end;
end;

function TLFastCGIClient.CreateRequester: TLFastCGIRequest;
begin
  if FRequests[FNextRequestID] = nil then
    FRequests[FNextRequestID] := TLFastCGIRequest.Create;
  Result := FRequests[FNextRequestID];
  Inc(FNextRequestID);
  Result.FClient := Self;
  Result.ID := FNextRequestID;  { request ids start at 1 }
end;

function TLFastCGIClient.Connect: Boolean;
begin
  Result := inherited Connect(FPool.Host, FPool.Port);
  FRequest := FRequests[0];
  if FRequest.FBuffer.Pos = FRequest.FBuffer.Memory then
    FRequest.SendGetValues;
  if FState <> fsStartingServer then
    FState := fsConnecting
  else
    FState := fsConnectingAgain;
end;

function TLFastCGIClient.BeginRequest(AType: integer): TLFastCGIRequest;
begin
  if FFreeRequest <> nil then
  begin
    Result := FFreeRequest.FNextFree;
    if FFreeRequest = FFreeRequest.FNextFree then
      FFreeRequest := nil
    else
      FFreeRequest.FNextFree := FFreeRequest.FNextFree.FNextFree;
    Result.FNextFree := nil;
  end else
  if FNextRequestID = FRequestsCount then
    exit(nil)
  else begin
    Result := CreateRequester;
  end;

  if not Connected then
    Connect;

  Result.SendBeginRequest(AType);
  Inc(FRequestsSent);
end;

procedure TLFastCGIClient.EndRequest(ARequest: TLFastCGIRequest);
begin
  if FFreeRequest <> nil then
    ARequest.FNextFree := FFreeRequest.FNextFree
  else
    FFreeRequest := ARequest;
  FFreeRequest.FNextFree := ARequest;
  if FPool <> nil then
    FPool.EndRequest(Self);
end;
   
{ TLFastCGIPool }

constructor TLFastCGIPool.Create;
begin
  FClientsMax := 1;
  FMaxRequestsConn := 1;
  inherited;
end;

destructor TLFastCGIPool.Destroy;
var
  I: integer;
begin
  for I := 0 to FClientsAvail-1 do
    FClients[I].Free;
  FreeMem(FClients);
  if FTimer <> nil then
    FTimer.Free;
  inherited;
end;

function  TLFastCGIPool.CreateClient: TLFastCGIClient;
begin
  if FClientsAvail = FClientsCount then
  begin
    Inc(FClientsCount, 64);
    ReallocMem(FClients, FClientsCount*sizeof(TLFastCGIRequest));
  end;
  Result := TLFastCGIClient.Create(nil);
  Result.FPool := Self;
  Result.Eventer := FEventer;
  FClients[FClientsAvail] := Result;
  Inc(FClientsAvail);
end;

function  TLFastCGIPool.BeginRequest(AType: integer): TLFastCGIRequest;
var
  lTempClient: TLFastCGIClient;
begin
  Result := nil;
  while FFreeClient <> nil do
  begin
    lTempClient := FFreeClient.FNextFree;
    Result := lTempClient.BeginRequest(AType);
    if Result <> nil then break;
    { Result = nil -> no free requesters on next free client }
    if lTempClient = FFreeClient then
      FFreeClient := nil
    else
      FFreeClient.FNextFree := lTempClient.FNextFree;
    lTempClient.FNextFree := nil;
  end;

  { all clients busy }
  if Result = nil then
    if FClientsAvail < FClientsMax then
      Result := CreateClient.BeginRequest(AType);
end;

procedure TLFastCGIPool.EndRequest(AClient: TLFastCGIClient);
begin
  { TODO: wait for other requests to be completed }
  if AClient.RequestsSent = FMaxRequestsConn then
    AClient.Disconnect;
  AddToFreeClients(AClient);
end;

procedure TLFastCGIPool.AddToFreeClients(AClient: TLFastCGIClient);
begin
  if AClient.FNextFree <> nil then exit;
  
  if FFreeClient = nil then
    FFreeClient := AClient
  else
    AClient.FNextFree := FFreeClient.FNextFree;
  FFreeClient.FNextFree := AClient;
end;

procedure TLFastCGIPool.ConnectClients(Sender: TObject);
var
  I: integer;
begin
  for I := 0 to FClientsAvail-1 do
    if FClients[I].FState = fsStartingServer then
      FClients[I].Connect;
end;

procedure TLFastCGIPool.StartServer;
begin
  if FSpawnState = ssNone then
  begin
    FSpawnState := ssSpawning;
    SpawnFCGIProcess(FAppName, FAppEnv, FPort);
    if FTimer = nil then
      FTimer := TLTimer.Create;
    FTimer.OneShot := true;
    FTimer.OnTimer := @ConnectClients;
  end;
  FTimer.Interval := 2000;
end;

end.