-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathHTTPServer.pas
508 lines (482 loc) · 18.6 KB
/
HTTPServer.pas
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
unit HTTPServer;
{******************************************************************************}
{* HTTP Server Unit *}
{* Revolutionary Confederation of Anarcho Syndicalists *}
{* Written by: black.rabbit 2011 *}
{******************************************************************************}
interface
{$I 'std.inc'}
uses
Windows, SysUtils, Variants, Classes,
Controls, ComCtrls, Gauges,
{ utils }
DateUtils, Utils, Strings, VarRecs, Versions, EClasses,
DllThreads,
{ synapse }
WinSock, BlckSock, SynaUtil;
{$I 'HTTP.inc'}
type
{ îøèáêà ñîêåòà }
{$M+}
ESocketError = class (Exception) end;
{$M-}
{ îøèáêà http-ñåðâåðà }
{$M+}
EHTTPServerError = class (EThreadError) end;
{$M-}
{ http-ñåðâåð }
{$M+}
CHTTPServer = class of THTTPServer;
PHTTPServer = ^THTTPServer;
THTTPServer = class (TDllThread)
public
class procedure _raise (anArgs: array of const;
const anEGUID: String = ''); override;
class procedure _raise (anArgs: array of const;
anEGUID: array of const); override;
private
f_Threads: TDllThreads; { äî÷åðíèå ïîòîêè }
f_Sock: TTCPBlockSocket; { ñîêåò }
f_Port: WORD; { ïîðò }
f_TimeOut: LongWord; { âðåìÿ îæèäàíèÿ ms }
public
constructor Create (anArgs: array of const); override;
destructor Destroy; override;
public
procedure Execute; override;
procedure Main; override;
procedure Return; override;
public
property Threads: TDllThreads read f_Threads;
property Sock: TTCPBlockSocket read f_Sock;
property Port: WORD read f_Port write f_Port;
property TimeOut: LongWord read f_TimeOut write f_TimeOut;
end;
{$M-}
{ äî÷åðíèé ïîòîê http-ñåðâåðà }
{$M+}
CHTTPServerThread = class of THTTPServerThread;
PHTTPServerThread = ^THTTPServerThread;
THTTPServerThread = class (TDllThread)
public
class procedure _raise (anArgs: array of const;
const anEGUID: String = ''); override;
class procedure _raise (anArgs: array of const;
anEGUID: array of const); override;
private
f_Sock: TTCPBlockSocket; { ñîêåò }
f_HSock: TSocket; { äèñêðèïòîð ñîêåòà }
f_TimeOut: LongWord; { âðåìÿ îæèäàíèÿ ms }
f_Headers: TStringList; { çàãîëîâîê }
f_InputData: TStream; { âõîäÿùèé ïîòîê }
f_OutputData: TStream; { èñõîäÿùèé ïîòîê }
f_Request: String; { çàïðîñ }
f_RequestSize: Int64; { ðàçìåð çàïðîñà }
f_Protocol: String; { ïðîòîêîë }
f_ProtocolVersion: String; { âåðñèÿ ïðîòîêîëà }
f_Method: String; { ìåòîä }
f_URI: String; { àäðåñ }
f_Host: String; { õîñò â çàãîëîâêå }
f_UserAgent: String; { áðàóçåð }
f_ResultCode: WORD; { êîä îòâåòà }
f_Closed : Boolean; { ïðèçíàê çàêðûòèÿ ñåññèè }
public
constructor Create (anArgs: array of const); override;
destructor Destroy; override;
public
procedure Main; override;
procedure Return; override;
function Process : WORD; virtual;
public
property Sock: TTCPBlockSocket read f_Sock;
property HSock: TSocket read f_HSock;
property TimeOut: LongWord read f_TimeOut write f_TimeOut;
property Headers: TStringList read f_Headers write f_Headers;
property InputData: TStream read f_InputData;
property OutputData: TStream read f_OutputData;
property Request: String read f_Request write f_Request;
property RequestSize: Int64 read f_RequestSize write f_RequestSize;
property Protocol: String read f_Protocol write f_Protocol;
property ProtocolVersion: String read f_ProtocolVersion write f_ProtocolVersion;
property Method: String read f_Method write f_Method;
property URI: String read f_URI write f_URI;
property Host: String read f_Host write f_Host;
property UserAgent: String read f_UserAgent write f_UserAgent;
property ResultCode: WORD read f_ResultCode write f_ResultCode;
property Closed : Boolean read f_Closed write f_Closed;
end;
{$M-}
{ THTTPServer Errors }
resourcestring
ERR_THTTPSERVER_CREATE = 'Îøèáêà ñîçäàíèÿ ïîòîêà âåá-ñåðâåðà!';
ERR_THTTPSERVER_DESTROY = 'Îøèáêà óíè÷òîæåíèÿ ïîòîêà âåá-ñåðâåðà!';
ERR_THTTPSERVER_EXECUTE = 'Îøèáêà âûïîëíåíèÿ ïîòîêà âåá-ñåðâåðà!';
ERR_THTTPSERVER_MAIN = 'Îøèáêà ãëàâíîé ôóíêöèè ïîòîêà!';
ERR_THTTPSERVER_RETURN = 'Îøèáêà ôóíêöèè âîçâðàòà ïîòîêà!';
ERR_THTTPSERVER_INVALID_PORT = 'Íåêîððåêòíûé ïîðò!';
ERR_THTTPSERVER_INVALID_TIMEOUT = 'Íåêîððåêòíîå âðåìÿ îæèäàíèÿ!';
{ THTTPServerThread Errors }
resourcestring
ERR_THTTPSERVERTHREAD_CREATE = 'Îøèáêà ñîçäàíèÿ äî÷åðíåãî ïîòîêà âåá-ñåðâåðà!';
ERR_THTTPSERVERTHREAD_DESTROY = 'Îøèáêà óíè÷òîæåíèÿ äî÷åðíåãî ïîòîêà âåá-ñåðâåðà!';
ERR_THTTPSERVERTHREAD_MAIN = 'Îøèáêà ãëàâíîé ôóíêöèè ïîòîêà!';
ERR_THTTPSERVERTHREAD_RETURN = 'Îøèáêà ôóíêöèè âîçâðàòà ïîòîêà!';
ERR_THTTPSERVERTHREAD_PROCESS = 'Îøèáêà îáðàáîòêè çàïðîñà!';
ERR_THTTPSERVERTHREAD_INVALID_SOCKET_ID = 'Íåêîððåêòíûé äèñêðèïòîð ñîêåòà!';
ERR_THTTPSERVERTHREAD_INVALID_TIMEOUT = 'Íåêîððåêòíîå âðåìÿ îæèäàíèÿ!';
ERR_THTTPSERVERTHREAD_SOCKET_ERROR = 'Îøèáêà ñîêåòà %d : %s';
ERR_THTTPSERVERTHREAD_IVALID_REQUEST = 'Íåêîððåêòíûé çàïðîñ!';
ERR_THTTPSERVERTHREAD_IVALID_PROTOCOL = 'Íåêîððåêòíûé ïðîòîêîë!';
ERR_THTTPSERVERTHREAD_IVALID_METHOD = 'Íåêîððåêòíûé ìåòîä!';
ERR_THTTPSERVERTHREAD_IVALID_URI = 'Íåêîððåêòíûé URI!';
implementation
{ THTTPServer }
class procedure THTTPServer._raise (anArgs: array of const;
const anEGUID: String = '');
begin
raise EHTTPServerError.Create ( _([self],anArgs), anEGUID );
end;
class procedure THTTPServer._raise (anArgs: array of const;
anEGUID: array of const);
begin
raise EHTTPServerError.Create ( _([self],anArgs), anEGUID );
end;
constructor THTTPServer.Create (anArgs: array of const);
var
I : Integer;
args : array_of_const;
begin
try
{ ïåðåäàåì ïàðàìåòðû ñîçäàíèÿ áàçîâîãî ïîòîêà,
íà÷èíàÿ ñ òðåòüåãî àðãóìåíòà }
if ( High (anArgs) >= 2 ) then
begin
SetLength ( Args, High (anArgs)-2 +1 );
for I := 2 to High (anArgs) do
args [I-2] := anArgs [I];
end
else
args := _array_of_const ([]);
inherited Create (args);
{ ÿâíî óêàçûâàåì íà íåîáõîäèìîñòü óíè÷òîæåíèÿ ïîòîêà ïî îêîí÷àíèþ ðàáîòû }
FreeOnTerminate := TRUE;
{ ïåðâûé ïàðàìåòð - ïîðò }
f_Port := 80;
if notEmpty (0,anArgs) then
begin
f_Port := toInteger (anArgs [0]);
end;
if ( Port <= 0 ) then
raise Exception.Create (ERR_THTTPSERVER_INVALID_PORT);
{ âòîðîé ïàðàìåòð - âðåìÿ îæèäàíèÿ }
f_TimeOut := 120000;
if notEmpty (1,anArgs) then
begin
f_TimeOut := toInteger (anArgs [1]);
end;
if ( TimeOut = 0 ) then
raise Exception.Create (ERR_THTTPSERVER_INVALID_TIMEOUT);
{ ñîçäàåì ñîêåò }
f_Sock := TTCPBlockSocket.Create;
{ ñîçäàåì êîíòåéíåð äî÷åðíèõ ïîòîêîâ }
f_Threads := TDllThreads.Create ([]);
except on E: Exception do
_raise ([ 'Create', ERR_THTTPSERVER_CREATE, E, Exception (FatalException) ],
['{5FE107FB-D71C-409E-9A75-22C9A1954E81}']);
end;
end;
destructor THTTPServer.Destroy;
begin
try
try
if Assigned (Threads) then
Threads.Terminate;
FreeAndNil (f_Threads);
if Assigned (Sock) then
Sock.CloseSocket;
FreeAndNil (f_Sock);
finally
inherited Destroy;
end;
except on E: Exception do
_raise ([ 'Destroy', ERR_THTTPSERVER_DESTROY, E, Exception (FatalException) ],
['{A628DCFC-4110-4ECE-875B-986E3048F208}']);
end;
end;
procedure THTTPServer.Execute;
begin
try
if Terminated then Exit;
{ ñëóøàåì âñå ip-àäðåñà íà âûáðàííîì ïîðòó }
with Sock do
begin
CreateSocket;
SetLinger (TRUE,10000);
Bind ( cAnyHost, IntToStr (Port) );
Listen;
inherited Execute;
end;
except on E: Exception do
_raise ([ 'Execute', ERR_THTTPSERVER_EXECUTE, E, Exception (FatalException) ],
['{439435B0-C284-47B0-85F9-448A36852261}']);
end;
end;
procedure THTTPServer.Main;
var
ClientSock : TSocket;
Thr : THTTPServerThread;
begin
try
if Terminated then Exit;
inherited Main;
with Sock do
begin
if CanRead (TimeOut) then
begin
ClientSock := Accept;
if ( LastError = 0 ) and ( ClientSock > 0 ) then
try
Thr := THTTPServerThread.Create ([ClientSock,TimeOut]);
if ( Threads.Add (Thr) < 0 ) then
FreeAndNil (Thr);
except
FreeAndNil (Thr);
end;
end;
end;
except on E: Exception do
_raise ([ 'Main', ERR_THTTPSERVER_MAIN, E, Exception (FatalException) ],
['{BBAF326A-FDFB-4C53-A177-6F63584BB8C3}']);
end;
end;
procedure THTTPServer.Return;
begin
try
if Terminated then Exit;
inherited Return;
except on E: Exception do
_raise ([ 'Return', ERR_THTTPSERVER_RETURN, E, Exception (FatalException) ],
['{DE336E65-E848-4F07-8FC3-6D25BCFBD2AD}']);
end;
end;
{ THTTPServerThread }
class procedure THTTPServerThread._raise (anArgs: array of const;
const anEGUID: String = '');
begin
raise EHTTPServerError.Create ( _([self],anArgs), anEGUID );
end;
class procedure THTTPServerThread._raise (anArgs: array of const;
anEGUID: array of const);
begin
raise EHTTPServerError.Create ( _([self],anArgs), anEGUID );
end;
constructor THTTPServerThread.Create (anArgs: array of const);
var
I : Integer;
args : array_of_const;
begin
try
{ ïåðåäàåì ïàðàìåòðû ñîçäàíèÿ áàçîâîãî ïîòîêà,
íà÷èíàÿ ñ òðåòüåãî àðãóìåíòà }
if ( High (anArgs) >= 2 ) then
begin
SetLength ( Args, High (anArgs)-2 +1 );
for I := 2 to High (anArgs) do
args [I-2] := anArgs [I];
end
else
args := _array_of_const ([]);
inherited Create (args);
{ ÿâíî óêàçûâàåì íà íåîáõîäèìîñòü óíè÷òîæåíèÿ ïîòîêà ïî îêîí÷àíèþ ðàáîòû }
FreeOnTerminate := TRUE;
{ ïåðâûé ïàðàìåòð - èäåíòèôèêàòîð ñîêåòà }
f_HSock := 0;
if notEmpty (0,anArgs) then
begin
f_HSock := toInteger (anArgs [0]);
end;
if ( HSock <= 0 ) then
raise Exception.Create (ERR_THTTPSERVERTHREAD_INVALID_SOCKET_ID);
{ âòîðîé ïàðàìåòð - âðåìÿ îæèäàíèÿ }
f_TimeOut := 120000;
if notEmpty (1,anArgs) then
begin
f_TimeOut := toInteger (anArgs [1]);
end;
if ( TimeOut = 0 ) then
raise Exception.Create (ERR_THTTPSERVERTHREAD_INVALID_TIMEOUT);
{ ñîçäàåì ñîêåò }
f_Sock := TTCPBlockSocket.Create;
Sock.Socket := HSock;
{ ñîçäàåì ñïèñîê çàãîëîâêîâ }
f_Headers := TStringList.Create;
{ ñîçäàåì ïîòîêè äàííûõ }
f_InputData := TMemoryStream.Create;
f_OutputData := TMemoryStream.Create;
except on E: Exception do
_raise ([ 'Create', ERR_THTTPSERVERTHREAD_CREATE, E, Exception (FatalException) ],
['{D064B326-0F5A-43F6-BAB2-F08198F63459}']);
end;
end;
destructor THTTPServerThread.Destroy;
begin
try
_FillChar ( f_Request, Length (f_Request), $00 );
_FillChar ( f_Protocol, Length (f_Protocol), $00 );
_FillChar ( f_ProtocolVersion, Length (f_ProtocolVersion), $00 );
_FillChar ( f_Method, Length (f_Method), $00 );
_FillChar ( f_URI, Length (f_URI), $00 );
_FillChar ( f_Host, Length (f_Host), $00 );
_FillChar ( f_UserAgent, Length (f_UserAgent), $00 );
if Assigned (Sock) then
Sock.CloseSocket;
FreeAndNil (f_Sock);
FreeAndNil (f_Headers);
FreeAndNil (f_InputData);
FreeAndNil (f_OutputData);
inherited Destroy;
except on E: Exception do
_raise ([ 'Destroy', ERR_THTTPSERVERTHREAD_DESTROY, E, Exception (FatalException) ],
['{0AF99A00-B2A4-4713-9954-B94E7D4AC1D9}']);
end;
end;
procedure THTTPServerThread.Main;
var
sz : LongWord;
S : String;
begin
try
if Terminated then Exit;
inherited Main;
with Sock do
begin
{ ÷èòàåì ïðîòîêîë HTTP-çàïðîñà }
Request := RecvString (TimeOut);
if ( LastError <> 0 ) then
raise ESocketError.CreateFmt (ERR_THTTPSERVERTHREAD_SOCKET_ERROR,[LastError,LastErrorDesc]);
if isEmpty (Request) then
raise Exception.Create (ERR_THTTPSERVERTHREAD_IVALID_REQUEST);
S := Request;
try
Method := Fetch (S,' ');
if isEmpty (Method) then
raise Exception.Create (ERR_THTTPSERVERTHREAD_IVALID_METHOD);
URI := Fetch (S,' ');
if isEmpty (URI) then
raise Exception.Create (ERR_THTTPSERVERTHREAD_IVALID_URI);
Protocol := Fetch (S,' ');
if isEmpty (Protocol) or ( Pos ('HTTP/',Protocol) <> 1 ) then
raise Exception.Create (ERR_THTTPSERVERTHREAD_IVALID_PROTOCOL);
ProtocolVersion := Copy ( Protocol, Length ('HTTP/')+1, Length (Protocol) );
finally
_FillChar ( S, Length (S), $00 );
end;
Headers.Clear;
Host := '';
UserAgent := '';
RequestSize := -1;
Closed := FALSE;
{ ÷èòàåì çàãîëîâîê HTTP-çàïðîñà }
repeat
ProcessMessages;
Request := RecvString (TimeOut);
if ( LastError <> 0 ) then
raise ESocketError.CreateFmt (ERR_THTTPSERVERTHREAD_SOCKET_ERROR,[LastError,LastErrorDesc]);
if not isEmpty (Request) then
Headers.Add (Request);
if ( Pos ( 'HOST:', UpperCase (Request) ) = 1 ) then
Host := SeparateRight (Request,' ');
if ( Pos ( 'USER-AGENT', UpperCase (Request) ) = 1 ) then
UserAgent := SeparateRight (Request,' ');
if ( Pos ( 'CONTENT-LENGTH:', UpperCase (Request) ) = 1 ) then
RequestSize := StrToIntDef ( SeparateRight (Request,' '), -1 );
Closed := ( Pos ( 'CONNECTION: CLOSE', UpperCase (Request) ) = 1 );
until ( Request = '' );
{ ÷èòàåì òåëî HTTP-çàïðîñà }
TMemoryStream (InputData).Clear;
if ( RequestSize >= 0 ) then
begin
TMemoryStream (InputData).SetSize (RequestSize);
sz := Sock.RecvBufferEx ( TMemoryStream (InputData).Memory, RequestSize, TimeOut );
if ( LastError <> 0 ) then
raise ESocketError.CreateFmt (ERR_THTTPSERVERTHREAD_SOCKET_ERROR,[LastError,LastErrorDesc]);
TMemoryStream (InputData).SetSize (sz);
end;
end;
except on E: Exception do
_raise ([ 'Main', ERR_THTTPSERVERTHREAD_MAIN, E, Exception (FatalException) ],
['{1BC1260D-7081-4871-A261-AFDF70B44536}']);
end;
end;
procedure THTTPServerThread.Return;
var
I : Integer;
begin
try
if Terminated then Exit;
inherited Return;
with Sock do
begin
{ îáðàáîòêà }
TMemoryStream (OutputData).Clear;
ResultCode := Process;
{ îòïðàâëÿåì ïðîòîêîë HTTP-îòâåòà }
SendString ( Format ('%s %d%s',[Protocol,ResultCode,CRLF]) );
if ( LastError <> 0 ) then
raise ESocketError.CreateFmt (ERR_THTTPSERVERTHREAD_SOCKET_ERROR,[LastError,LastErrorDesc]);
{ îòïðàâëÿåì çàãîëîâîê HTTP-îòâåòà }
Headers.Add ( Format ('Content-length: %d',[OutputData.Size]) );
if Closed then
Headers.Add ('Connection: close');
Headers.Add ( Format ('Date: %s',[ Rfc822DateTime (now) ]) );
Headers.Add ( Format ('Server: %s',[ProjectName]) );
Headers.Add ('');
for I := 0 to Headers.count - 1 do
begin
SendString ( Headers [I] + CRLF);
if ( LastError <> 0 ) then
raise ESocketError.CreateFmt (ERR_THTTPSERVERTHREAD_SOCKET_ERROR,[LastError,LastErrorDesc]);
end;
{ îòïðàâëÿåì òåëî HTTP-îòâåòà }
SendBuffer ( TMemoryStream (OutputData).Memory, OutputData.Size );
if ( LastError <> 0 ) then
raise ESocketError.CreateFmt (ERR_THTTPSERVERTHREAD_SOCKET_ERROR,[LastError,LastErrorDesc]);
if Closed then
Terminate;
end;
except on E: Exception do
_raise ([ 'Return', ERR_THTTPSERVERTHREAD_RETURN, E, Exception (FatalException) ],
['{F896CC45-8213-4DB4-BE32-FD843EE543FA}']);
end;
end;
function THTTPServerThread.Process : WORD;
var
Body : TStringList;
begin
Result := HTTP_STATUS_INTERNAL_SERVER_ERROR;
try
Headers.Clear;
Headers.Add ('Content-type: Text/Html');
Body := TStringList.Create;
try
Body.Add ('<html>');
Body.Add ('<head></head>');
Body.Add ('<body>');
Body.Add (ProductName);
Body.Add ('<br>');
Body.Add (CompanyName);
Body.Add ('<br>');
Body.Add ( Format ('Written by: %s',[CopyRight]) );
Body.Add ('</body>');
Body.Add ('</html>');
Body.SaveToStream (OutputData);
Result := HTTP_STATUS_OK;
finally
FreeAndNil (Body);
end;
except on E: Exception do
_raise ([ 'Process', ERR_THTTPSERVERTHREAD_PROCESS, E, Exception (FatalException) ],
['{AB972A88-E8C8-48CB-8844-247859E4FDD6}']);
end;
end;
end.