BrookHTTPServer.pas 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075
  1. (* _ _
  2. * | |__ _ __ ___ ___ | | __
  3. * | '_ \| '__/ _ \ / _ \| |/ /
  4. * | |_) | | | (_) | (_) | <
  5. * |_.__/|_| \___/ \___/|_|\_\
  6. *
  7. * Microframework which helps to develop web Pascal applications.
  8. *
  9. * Copyright (c) 2012-2021 Silvio Clecio <[email protected]>
  10. *
  11. * Brook framework is free software; you can redistribute it and/or
  12. * modify it under the terms of the GNU Lesser General Public
  13. * License as published by the Free Software Foundation; either
  14. * version 2.1 of the License, or (at your option) any later version.
  15. *
  16. * Brook framework is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  19. * Lesser General Public License for more details.
  20. *
  21. * You should have received a copy of the GNU Lesser General Public
  22. * License along with Brook framework; if not, write to the Free Software
  23. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  24. *)
  25. { Contains classes which composes a fast event-driven HTTP(S) server. }
  26. unit BrookHTTPServer;
  27. {$I BrookDefines.inc}
  28. interface
  29. uses
  30. SysUtils,
  31. Classes,
  32. Marshalling,
  33. libsagui,
  34. BrookUtility,
  35. BrookHandledClasses,
  36. BrookExtra,
  37. BrookHTTPAuthentication,
  38. BrookHTTPRequest,
  39. BrookHTTPResponse;
  40. resourcestring
  41. { Error message @code('Active server.'). }
  42. SBrookActiveServer = 'Active server.';
  43. { Error message @code('Cannot create server handle.'). }
  44. SBrookCannotCreateServerHandle = 'Cannot create server handle.';
  45. { Error message @code('TLS is not available.'). }
  46. SBrookTLSNotAvailable = Concat(
  47. 'TLS is not available. Please download the Sagui library with ',
  48. 'TLS support at: https://github.com/risoflora/libsagui/releases');
  49. { Error message @code('Private key cannot be empty.'). }
  50. SBrookEmptyPrivateKey = 'Private key cannot be empty.';
  51. { Error message @code('Certificate cannot be empty.'). }
  52. SBrookEmptyCertificate = 'Certificate cannot be empty.';
  53. type
  54. { Handles exceptions related to HTTP server security. }
  55. EBrookHTTPServerSecurity = class(Exception);
  56. { Class which holds the TLS properties for the HTTPS server. }
  57. TBrookHTTPServerSecurity = class(TPersistent)
  58. private
  59. FActive: Boolean;
  60. FPrivateKey: string;
  61. FPrivatePassword: string;
  62. FCertificate: string;
  63. FTrust: string;
  64. FDHParams: string;
  65. function IsActiveStored: Boolean;
  66. public
  67. { Copies properties from another security source.
  68. @param(ASource[in] Security source.) }
  69. procedure Assign(ASource: TPersistent); override;
  70. { Clears the common TLS properties. }
  71. procedure Clear; virtual;
  72. { Validates the common TLS properties. }
  73. procedure Validate; {$IFNDEF DEBUG}inline;{$ENDIF}
  74. published
  75. { Activates the TLS support. }
  76. property Active: Boolean read FActive write FActive stored IsActiveStored;
  77. { Content of the private key (key.pem) to be used by the HTTPS server. }
  78. property PrivateKey: string read FPrivateKey write FPrivateKey;
  79. { Password of the private key. }
  80. property PrivatePassword: string read FPrivatePassword
  81. write FPrivatePassword;
  82. { Content of the certificate (cert.pem) to be used by the HTTPS server. }
  83. property Certificate: string read FCertificate write FCertificate;
  84. { Content of the certificate (ca.pem) to be used by the HTTPS server for
  85. client authentication. }
  86. property Trust: string read FTrust write FTrust;
  87. { Content of the Diffie-Hellman parameters (dh.pem) to be used by the HTTPS
  88. server for key exchange. }
  89. property DHParams: string read FDHParams write FDHParams;
  90. end;
  91. { Event signature used by HTTP server to handle the clients authentication. }
  92. TBrookHTTPAuthenticateEvent = function(ASender: TObject;
  93. AAuthentication: TBrookHTTPAuthentication; ARequest: TBrookHTTPRequest;
  94. AResponse: TBrookHTTPResponse): Boolean of object;
  95. { Event signature used by HTTP server to handle errors in the clients
  96. authentication. }
  97. TBrookHTTPAuthenticateErrorEvent = procedure(ASender: TObject;
  98. AAuthentication: TBrookHTTPAuthentication; ARequest: TBrookHTTPRequest;
  99. AResponse: TBrookHTTPResponse; AException: Exception) of object;
  100. { Event signature used by HTTP server to handle requests. }
  101. TBrookHTTPRequestEvent = procedure(ASender: TObject;
  102. ARequest: TBrookHTTPRequest; AResponse: TBrookHTTPResponse) of object;
  103. { Event signature used by HTTP server to handle error in the requests. }
  104. TBrookHTTPRequestErrorEvent = procedure(ASender: TObject;
  105. ARequest: TBrookHTTPRequest; AResponse: TBrookHTTPResponse;
  106. AException: Exception) of object;
  107. { Event signature used by HTTP server to handle client connection events. }
  108. TBrookHTTPServerClientConnectionEvent = procedure(ASender: TObject;
  109. const AClient: Pointer; var AClosed: Boolean) of object;
  110. { Handles exceptions related to HTTP server. }
  111. EBrookHTTPServer = class(Exception);
  112. { Fast event-driven HTTP(S) server class. }
  113. TBrookHTTPServer = class(TBrookHandledComponent)
  114. private
  115. FHandle: Psg_httpsrv;
  116. FAuthenticated: Boolean;
  117. FConnectionLimit: Cardinal;
  118. FConnectionTimeout: Cardinal;
  119. FNoFavicon: Boolean;
  120. FPayloadLimit: NativeUInt;
  121. FUploadsLimit: UInt64;
  122. FActive: Boolean;
  123. FPort: UInt16;
  124. FPostBufferSize: NativeUInt;
  125. FThreaded: Boolean;
  126. FStreamedActive: Boolean;
  127. FStreamedAuthenticated: Boolean;
  128. FThreadPoolSize: Cardinal;
  129. FUploadsDir: string;
  130. FLocker: TBrookLocker;
  131. FSecurity: TBrookHTTPServerSecurity;
  132. FOnAuthenticate: TBrookHTTPAuthenticateEvent;
  133. FOnAuthenticateError: TBrookHTTPAuthenticateErrorEvent;
  134. FOnRequest: TBrookHTTPRequestEvent;
  135. FOnRequestError: TBrookHTTPRequestErrorEvent;
  136. FOnClientConnection: TBrookHTTPServerClientConnectionEvent;
  137. FOnError: TBrookErrorEvent;
  138. FOnStart: TNotifyEvent;
  139. FOnStop: TNotifyEvent;
  140. function GetConnectionLimit: Cardinal;
  141. function GetConnectionTimeout: Cardinal;
  142. function GetPayloadLimit: NativeUInt;
  143. function GetUploadsLimit: UInt64;
  144. function GetPort: UInt16;
  145. function GetPostBufferSize: NativeUInt;
  146. function GetThreaded: Boolean;
  147. function GetThreadPoolSize: Cardinal;
  148. function GetUploadsDir: string;
  149. function IsActiveStored: Boolean;
  150. function IsAuthenticatedStored: Boolean;
  151. function IsConnectionLimitStored: Boolean;
  152. function IsConnectionTimeoutStored: Boolean;
  153. function IsNoFaviconStored: Boolean;
  154. function IsPayloadLimitStored: Boolean;
  155. function IsUploadsLimitStored: Boolean;
  156. function IsPortStored: Boolean;
  157. function IsPostBufferSizeStored: Boolean;
  158. function IsThreadedStored: Boolean;
  159. function IsThreadPoolSizeStored: Boolean;
  160. function IsUploadsDirStored: Boolean;
  161. procedure SetAuthenticated(AValue: Boolean);
  162. procedure SetConnectionLimit(AValue: Cardinal);
  163. procedure SetConnectionTimeout(AValue: Cardinal);
  164. procedure SetPayloadLimit(AValue: NativeUInt);
  165. procedure SetLocker(AValue: TBrookLocker);
  166. procedure SetSecurity(AValue: TBrookHTTPServerSecurity);
  167. procedure SetUploadsLimit(AValue: UInt64);
  168. procedure SetPort(AValue: UInt16);
  169. procedure SetPostBufferSize(AValue: NativeUInt);
  170. procedure SetThreaded(AValue: Boolean);
  171. procedure SetThreadPoolSize(AValue: Cardinal);
  172. procedure SetUploadsDir(const AValue: string);
  173. procedure InternalCreateServerHandle; {$IFNDEF DEBUG}inline;{$ENDIF}
  174. procedure InternalFreeServerHandle; {$IFNDEF DEBUG}inline;{$ENDIF}
  175. procedure InternalShutdownServer; {$IFNDEF DEBUG}inline;{$ENDIF}
  176. procedure InternalCheckServerOption(Aret: cint);
  177. {$IFNDEF DEBUG}inline;{$ENDIF}
  178. procedure InternalLibUnloadEvent(ASender: TObject);
  179. protected
  180. class function DoAuthenticationCallback(Acls: Pcvoid; Aauth: Psg_httpauth;
  181. Areq: Psg_httpreq; Ares: Psg_httpres): cbool; cdecl; static;
  182. class procedure DoRequestCallback(Acls: Pcvoid; Areq: Psg_httpreq;
  183. Ares: Psg_httpres); cdecl; static;
  184. class procedure DoClientConnectionCallback(Acls: Pcvoid;
  185. const Aclient: Pcvoid; Aclosed: Pcbool); cdecl; static;
  186. class procedure DoErrorCallback(Acls: Pcvoid;
  187. const Aerr: Pcchar); cdecl; static;
  188. function CreateLocker: TBrookLocker; virtual;
  189. function CreateAuthentication(
  190. AHandle: Pointer): TBrookHTTPAuthentication; virtual;
  191. function CreateSecurity: TBrookHTTPServerSecurity; virtual;
  192. function CreateRequest(AHandle: Pointer): TBrookHTTPRequest; virtual;
  193. function CreateResponse(AHandle: Pointer): TBrookHTTPResponse; virtual;
  194. function CreateError(const AMessage: string): Exception; virtual;
  195. procedure HandleAuthenticateError(AAuthentication: TBrookHTTPAuthentication;
  196. ARequest: TBrookHTTPRequest; AResponse: TBrookHTTPResponse;
  197. AException: Exception); virtual;
  198. function HandleAuthenticate(AAuthentication: TBrookHTTPAuthentication;
  199. ARequest: TBrookHTTPRequest;
  200. AResponse: TBrookHTTPResponse): Boolean; virtual;
  201. procedure HandleRequestError(ARequest: TBrookHTTPRequest;
  202. AResponse: TBrookHTTPResponse; AException: Exception); virtual;
  203. procedure HandleRequest(ARequest: TBrookHTTPRequest;
  204. AResponse: TBrookHTTPResponse); virtual;
  205. procedure HandleClientConnection(ASender: TObject; const AClient: Pointer;
  206. var AClosed: Boolean); virtual;
  207. procedure HandleError(ASender: TObject; AException: Exception); virtual;
  208. procedure Loaded; override;
  209. function GetHandle: Pointer; override;
  210. function GetMHDHandle: Pointer; virtual;
  211. procedure DoError(ASender: TObject; AException: Exception); virtual;
  212. function DoAuthenticate(ASender: TObject;
  213. AAuthentication: TBrookHTTPAuthentication; ARequest: TBrookHTTPRequest;
  214. AResponse: TBrookHTTPResponse): Boolean; virtual;
  215. procedure DoAuthenticateError(ASender: TObject;
  216. AAuthentication: TBrookHTTPAuthentication; ARequest: TBrookHTTPRequest;
  217. AResponse: TBrookHTTPResponse; AException: Exception); virtual;
  218. procedure DoRequest(ASender: TObject; ARequest: TBrookHTTPRequest;
  219. AResponse: TBrookHTTPResponse); virtual;
  220. procedure DoRequestError(ASender: TObject; ARequest: TBrookHTTPRequest;
  221. AResponse: TBrookHTTPResponse; AException: Exception); virtual;
  222. procedure DoClientConnection(ASender: TObject; const AClient: Pointer;
  223. var AClosed: Boolean); virtual;
  224. procedure CheckInactive; {$IFNDEF DEBUG}inline;{$ENDIF}
  225. procedure SetActive(AValue: Boolean); virtual;
  226. procedure DoOpen; virtual;
  227. procedure DoClose; virtual;
  228. public
  229. { Creates an instance of @code(TBrookHTTPServer).
  230. @param(AOwner[in] Owner component.) }
  231. constructor Create(AOwner: TComponent); override;
  232. { Destroys an instance of @code(TBrookHTTPServer). }
  233. destructor Destroy; override;
  234. { Starts the HTTP(S) server. }
  235. procedure Open;
  236. { Stops the HTTP(S) server. }
  237. procedure Close;
  238. { Locks all other requests. }
  239. procedure Lock; {$IFNDEF DEBUG}inline;{$ENDIF}
  240. { Unlocks all other requests. }
  241. procedure Unlock; {$IFNDEF DEBUG}inline;{$ENDIF}
  242. { Contains the MHD instance. }
  243. property MHDHandle: Pointer read GetMHDHandle;
  244. published
  245. { Activates the HTTP(S) server. }
  246. property Active: Boolean read FActive write SetActive stored IsActiveStored;
  247. { Enables/disables the basic HTTP authentication. }
  248. property Authenticated: Boolean read FAuthenticated write SetAuthenticated
  249. stored IsAuthenticatedStored;
  250. { Port for listening to connections. }
  251. property Port: UInt16 read GetPort write SetPort stored IsPortStored
  252. default 0;
  253. { Enables/disables the threaded model. If @true, the server creates one
  254. thread per connection. }
  255. property Threaded: Boolean read GetThreaded write SetThreaded
  256. stored IsThreadedStored default False;
  257. { Directory to store the uploaded files. }
  258. property UploadsDir: string read GetUploadsDir write SetUploadsDir
  259. stored IsUploadsDirStored;
  260. { Post buffering size. }
  261. property PostBufferSize: NativeUInt read GetPostBufferSize
  262. write SetPostBufferSize stored IsPostBufferSizeStored
  263. default BROOK_POST_BUFFER_SIZE;
  264. { Total payload limit. Use zero for no limit. }
  265. property PayloadLimit: NativeUInt read GetPayloadLimit write SetPayloadLimit
  266. stored IsPayloadLimitStored default BROOK_PAYLOAD_LIMIT;
  267. { Total uploads limit. Use zero for no limit. }
  268. property UploadsLimit: UInt64 read GetUploadsLimit write SetUploadsLimit
  269. stored IsUploadsLimitStored default BROOK_UPLOADS_LIMIT;
  270. { Thread pool size. Size greater than 1 enables the thread pooling. }
  271. property ThreadPoolSize: Cardinal read GetThreadPoolSize
  272. write SetThreadPoolSize stored IsThreadPoolSizeStored default 0;
  273. { Inactivity time (in seconds) to a client get time out. }
  274. property ConnectionTimeout: Cardinal read GetConnectionTimeout
  275. write SetConnectionTimeout stored IsConnectionTimeoutStored default 0;
  276. { Concurrent connections limit. Use zero for no limit. }
  277. property ConnectionLimit: Cardinal read GetConnectionLimit
  278. write SetConnectionLimit stored IsConnectionLimitStored default 0;
  279. { Enables/disables the favicon handling. If @true, it avoids @code(404) errors
  280. by sending an empty content (@code(204)) if path is @code('/favicon.ico'). }
  281. property NoFavicon: Boolean read FNoFavicon write FNoFavicon
  282. stored IsNoFaviconStored default False;
  283. { Allows to lock other requests from accessing a block of code. }
  284. property Locker: TBrookLocker read FLocker write SetLocker;
  285. { Holds the TLS properties for the HTTPS server. }
  286. property Security: TBrookHTTPServerSecurity read FSecurity
  287. write SetSecurity;
  288. { Event triggered when a client requests authentication. }
  289. property OnAuthenticate: TBrookHTTPAuthenticateEvent read FOnAuthenticate
  290. write FOnAuthenticate;
  291. { Event triggered when a client authentication raises errors. }
  292. property OnAuthenticateError: TBrookHTTPAuthenticateErrorEvent
  293. read FOnAuthenticateError write FOnAuthenticateError;
  294. { Event triggered when a client requests a content. }
  295. property OnRequest: TBrookHTTPRequestEvent read FOnRequest write FOnRequest;
  296. { Event triggered when a client request raises errors. }
  297. property OnRequestError: TBrookHTTPRequestErrorEvent read FOnRequestError
  298. write FOnRequestError;
  299. { Event triggered when a client connects to or disconnects from the server. }
  300. property OnClientConnection: TBrookHTTPServerClientConnectionEvent
  301. read FOnClientConnection write FOnClientConnection;
  302. { Event triggered when the HTTP server raises errors. }
  303. property OnError: TBrookErrorEvent read FOnError write FOnError;
  304. { Event triggered when the HTTP server starts successfully. }
  305. property OnStart: TNotifyEvent read FOnStart write FOnStart;
  306. { Event triggered when the HTTP server stops successfully. }
  307. property OnStop: TNotifyEvent read FOnStop write FOnStop;
  308. end;
  309. implementation
  310. { TBrookHTTPServerSecurity }
  311. procedure TBrookHTTPServerSecurity.Assign(ASource: TPersistent);
  312. var
  313. VSource: TBrookHTTPServerSecurity;
  314. begin
  315. if ASource is TBrookHTTPServerSecurity then
  316. begin
  317. VSource := ASource as TBrookHTTPServerSecurity;
  318. FPrivateKey := VSource.PrivateKey;
  319. FPrivatePassword := VSource.PrivatePassword;
  320. FCertificate := VSource.Certificate;
  321. FTrust := VSource.Trust;
  322. FDHParams := VSource.DHParams;
  323. end
  324. else
  325. inherited Assign(ASource);
  326. end;
  327. function TBrookHTTPServerSecurity.IsActiveStored: Boolean;
  328. begin
  329. Result := FActive;
  330. end;
  331. procedure TBrookHTTPServerSecurity.Validate;
  332. begin
  333. if FPrivateKey.IsEmpty then
  334. raise EBrookHTTPServerSecurity.Create(SBrookEmptyPrivateKey);
  335. if FCertificate.IsEmpty then
  336. raise EBrookHTTPServerSecurity.Create(SBrookEmptyCertificate);
  337. end;
  338. procedure TBrookHTTPServerSecurity.Clear;
  339. begin
  340. FActive := False;
  341. FPrivateKey := '';
  342. FPrivatePassword := '';
  343. FCertificate := '';
  344. FTrust := '';
  345. FDHParams := '';
  346. end;
  347. { TBrookHTTPServer }
  348. constructor TBrookHTTPServer.Create(AOwner: TComponent);
  349. begin
  350. inherited Create(AOwner);
  351. FLocker := CreateLocker;
  352. FSecurity := CreateSecurity;
  353. SgLib.UnloadEvents.Add(InternalLibUnloadEvent, Self);
  354. FPostBufferSize := BROOK_POST_BUFFER_SIZE;
  355. FPayloadLimit := BROOK_PAYLOAD_LIMIT;
  356. FUploadsLimit := BROOK_UPLOADS_LIMIT;
  357. end;
  358. destructor TBrookHTTPServer.Destroy;
  359. begin
  360. try
  361. SetActive(False);
  362. finally
  363. FSecurity.Free;
  364. SgLib.UnloadEvents.Remove(InternalLibUnloadEvent);
  365. FLocker.Free;
  366. inherited Destroy;
  367. end;
  368. end;
  369. procedure TBrookHTTPServer.Lock;
  370. begin
  371. FLocker.Lock;
  372. end;
  373. procedure TBrookHTTPServer.Unlock;
  374. begin
  375. FLocker.Unlock;
  376. end;
  377. procedure TBrookHTTPServer.InternalCreateServerHandle;
  378. var
  379. VACb: sg_httpauth_cb;
  380. begin
  381. if FAuthenticated then
  382. VACb := DoAuthenticationCallback
  383. else
  384. VACb := nil;
  385. FHandle := sg_httpsrv_new2(VACb, DoRequestCallback, DoErrorCallback, Self);
  386. if not Assigned(FHandle) then
  387. raise EInvalidPointer.Create(SBrookCannotCreateServerHandle);
  388. end;
  389. procedure TBrookHTTPServer.InternalFreeServerHandle;
  390. begin
  391. sg_httpsrv_free(FHandle);
  392. FHandle := nil;
  393. end;
  394. procedure TBrookHTTPServer.InternalShutdownServer;
  395. begin
  396. sg_httpsrv_shutdown(FHandle);
  397. end;
  398. procedure TBrookHTTPServer.InternalCheckServerOption(Aret: cint);
  399. begin
  400. if Aret <> 0 then
  401. begin
  402. InternalFreeServerHandle;
  403. SgLib.CheckLastError(Aret);
  404. end;
  405. end;
  406. function TBrookHTTPServer.CreateLocker: TBrookLocker;
  407. begin
  408. Result := TBrookLocker.Create;
  409. end;
  410. function TBrookHTTPServer.CreateAuthentication(
  411. AHandle: Pointer): TBrookHTTPAuthentication;
  412. begin
  413. Result := TBrookHTTPAuthentication.Create(AHandle);
  414. end;
  415. function TBrookHTTPServer.CreateSecurity: TBrookHTTPServerSecurity;
  416. begin
  417. Result := TBrookHTTPServerSecurity.Create;
  418. end;
  419. function TBrookHTTPServer.CreateRequest(AHandle: Pointer): TBrookHTTPRequest;
  420. begin
  421. Result := TBrookHTTPRequest.Create(AHandle);
  422. end;
  423. function TBrookHTTPServer.CreateResponse(AHandle: Pointer): TBrookHTTPResponse;
  424. begin
  425. Result := TBrookHTTPResponse.Create(AHandle);
  426. end;
  427. function TBrookHTTPServer.CreateError(const AMessage: string): Exception;
  428. begin
  429. Result := EBrookHTTPServer.Create(AMessage);
  430. end;
  431. class function TBrookHTTPServer.DoAuthenticationCallback(Acls: Pcvoid;
  432. Aauth: Psg_httpauth; Areq: Psg_httpreq; Ares: Psg_httpres): cbool; cdecl;
  433. var
  434. VSrv: TBrookHTTPServer;
  435. VAuth: TBrookHTTPAuthentication;
  436. VReq: TBrookHTTPRequest;
  437. VRes: TBrookHTTPResponse;
  438. begin
  439. VSrv := Acls;
  440. VReq := VSrv.CreateRequest(Areq);
  441. VRes := VSrv.CreateResponse(Ares);
  442. try
  443. if VSrv.FNoFavicon and VReq.IsFavicon then
  444. Exit(True);
  445. VAuth := VSrv.CreateAuthentication(Aauth);
  446. try
  447. VSrv.Lock;
  448. try
  449. Result := VSrv.HandleAuthenticate(VAuth, VReq, VRes);
  450. finally
  451. VSrv.Unlock;
  452. end;
  453. finally
  454. VAuth.Free;
  455. end;
  456. finally
  457. VRes.Free;
  458. VReq.Free;
  459. end;
  460. end;
  461. class procedure TBrookHTTPServer.DoRequestCallback(Acls: Pcvoid;
  462. Areq: Psg_httpreq; Ares: Psg_httpres); cdecl;
  463. var
  464. VSrv: TBrookHTTPServer;
  465. VReq: TBrookHTTPRequest;
  466. VRes: TBrookHTTPResponse;
  467. begin
  468. VSrv := Acls;
  469. VReq := VSrv.CreateRequest(Areq);
  470. VRes := VSrv.CreateResponse(Ares);
  471. try
  472. if VSrv.FNoFavicon and VReq.IsFavicon then
  473. VRes.SendEmpty
  474. else
  475. begin
  476. VSrv.Lock;
  477. try
  478. VSrv.HandleRequest(VReq, VRes);
  479. finally
  480. VSrv.Unlock;
  481. end;
  482. if VRes.IsEmpty and (not VReq.IsIsolated) then
  483. VRes.SendEmpty;
  484. end;
  485. finally
  486. VRes.Free;
  487. VReq.Free;
  488. end;
  489. end;
  490. class procedure TBrookHTTPServer.DoClientConnectionCallback(Acls: Pcvoid;
  491. const Aclient: Pcvoid; Aclosed: Pcbool); cdecl;
  492. var
  493. VSrv: TBrookHTTPServer;
  494. begin
  495. VSrv := Acls;
  496. VSrv.Lock;
  497. try
  498. VSrv.HandleClientConnection(VSrv, Aclient, PBoolean(Aclosed)^);
  499. finally
  500. VSrv.Unlock;
  501. end;
  502. end;
  503. class procedure TBrookHTTPServer.DoErrorCallback(Acls: Pcvoid;
  504. const Aerr: Pcchar); cdecl;
  505. var
  506. VSrv: TBrookHTTPServer;
  507. VExcept: Exception;
  508. begin
  509. VSrv := Acls;
  510. VExcept := VSrv.CreateError(TMarshal.ToString(Aerr));
  511. try
  512. VSrv.Lock;
  513. try
  514. VSrv.HandleError(VSrv, VExcept);
  515. finally
  516. VSrv.Unlock;
  517. end;
  518. finally
  519. VExcept.Free;
  520. end;
  521. end;
  522. procedure TBrookHTTPServer.CheckInactive;
  523. begin
  524. if (not (csLoading in ComponentState)) and Active then
  525. raise EInvalidOpException.Create(SBrookActiveServer);
  526. end;
  527. procedure TBrookHTTPServer.InternalLibUnloadEvent(ASender: TObject);
  528. begin
  529. if Assigned(ASender) then
  530. TBrookHTTPServer(ASender).Close;
  531. end;
  532. procedure TBrookHTTPServer.HandleAuthenticateError(
  533. AAuthentication: TBrookHTTPAuthentication; ARequest: TBrookHTTPRequest;
  534. AResponse: TBrookHTTPResponse; AException: Exception);
  535. begin
  536. AResponse.Reset;
  537. try
  538. DoAuthenticateError(Self, AAuthentication, ARequest, AResponse, AException);
  539. except
  540. on E: Exception do
  541. AResponse.Send(E.Message, BROOK_CT_TEXT_PLAIN, 500);
  542. end;
  543. end;
  544. function TBrookHTTPServer.HandleAuthenticate(
  545. AAuthentication: TBrookHTTPAuthentication; ARequest: TBrookHTTPRequest;
  546. AResponse: TBrookHTTPResponse): Boolean;
  547. begin
  548. try
  549. Result := DoAuthenticate(Self, AAuthentication, ARequest, AResponse);
  550. except
  551. on E: Exception do
  552. begin
  553. Result := False;
  554. HandleAuthenticateError(AAuthentication, ARequest, AResponse, E);
  555. end;
  556. end;
  557. end;
  558. procedure TBrookHTTPServer.HandleRequestError(ARequest: TBrookHTTPRequest;
  559. AResponse: TBrookHTTPResponse; AException: Exception);
  560. begin
  561. AResponse.Reset;
  562. try
  563. DoRequestError(Self, ARequest, AResponse, AException);
  564. except
  565. on E: Exception do
  566. AResponse.Send(E.Message, BROOK_CT_TEXT_PLAIN, 500);
  567. end;
  568. end;
  569. procedure TBrookHTTPServer.HandleRequest(ARequest: TBrookHTTPRequest;
  570. AResponse: TBrookHTTPResponse);
  571. begin
  572. try
  573. DoRequest(Self, ARequest, AResponse);
  574. except
  575. on E: Exception do
  576. HandleRequestError(ARequest, AResponse, E);
  577. end;
  578. end;
  579. procedure TBrookHTTPServer.HandleClientConnection(ASender: TObject;
  580. const AClient: Pointer; var AClosed: Boolean);
  581. begin
  582. DoClientConnection(ASender, AClient, AClosed);
  583. end;
  584. procedure TBrookHTTPServer.HandleError(ASender: TObject; AException: Exception);
  585. begin
  586. DoError(ASender, AException);
  587. end;
  588. procedure TBrookHTTPServer.Loaded;
  589. begin
  590. inherited Loaded;
  591. try
  592. if FStreamedAuthenticated then
  593. SetAuthenticated(True);
  594. if FStreamedActive then
  595. SetActive(True);
  596. except
  597. if csDesigning in ComponentState then
  598. begin
  599. if Assigned(ApplicationHandleException) then
  600. ApplicationHandleException(ExceptObject)
  601. else
  602. ShowException(ExceptObject, ExceptAddr);
  603. end
  604. else
  605. raise;
  606. end;
  607. end;
  608. function TBrookHTTPServer.GetHandle: Pointer;
  609. begin
  610. Result := FHandle;
  611. end;
  612. function TBrookHTTPServer.GetMHDHandle: Pointer;
  613. begin
  614. SgLib.Check;
  615. Result := sg_httpsrv_handle(FHandle);
  616. end;
  617. procedure TBrookHTTPServer.DoError(ASender: TObject;
  618. AException: Exception);
  619. begin
  620. if Assigned(FOnError) then
  621. FOnError(ASender, AException)
  622. else
  623. if Assigned(ApplicationShowException) then
  624. ApplicationShowException(AException)
  625. else if Assigned(ApplicationHandleException) then
  626. ApplicationHandleException(AException)
  627. else
  628. ShowException(AException, Pointer(AException));
  629. end;
  630. function TBrookHTTPServer.DoAuthenticate(ASender: TObject;
  631. AAuthentication: TBrookHTTPAuthentication; ARequest: TBrookHTTPRequest;
  632. AResponse: TBrookHTTPResponse): Boolean;
  633. begin
  634. Result := Assigned(FOnAuthenticate) and
  635. FOnAuthenticate(ASender, AAuthentication, ARequest, AResponse);
  636. end;
  637. procedure TBrookHTTPServer.DoAuthenticateError(ASender: TObject;
  638. AAuthentication: TBrookHTTPAuthentication; ARequest: TBrookHTTPRequest;
  639. AResponse: TBrookHTTPResponse; AException: Exception);
  640. begin
  641. if Assigned(FOnAuthenticateError) then
  642. FOnAuthenticateError(ASender, AAuthentication, ARequest, AResponse,
  643. AException)
  644. else
  645. HandleRequestError(ARequest, AResponse, AException);
  646. end;
  647. procedure TBrookHTTPServer.DoRequest(ASender: TObject;
  648. ARequest: TBrookHTTPRequest; AResponse: TBrookHTTPResponse);
  649. begin
  650. if Assigned(FOnRequest) then
  651. FOnRequest(ASender, ARequest, AResponse)
  652. else
  653. AResponse.SendEmpty;
  654. end;
  655. procedure TBrookHTTPServer.DoRequestError(ASender: TObject;
  656. ARequest: TBrookHTTPRequest; AResponse: TBrookHTTPResponse;
  657. AException: Exception);
  658. begin
  659. if Assigned(FOnRequestError) then
  660. FOnRequestError(ASender, ARequest, AResponse, AException)
  661. else
  662. AResponse.Send(AException.Message, BROOK_CT_TEXT_PLAIN, 500);
  663. end;
  664. procedure TBrookHTTPServer.DoClientConnection(ASender: TObject;
  665. const AClient: Pointer; var AClosed: Boolean);
  666. begin
  667. if Assigned(FOnClientConnection) then
  668. FOnClientConnection(ASender, AClient, AClosed);
  669. end;
  670. procedure TBrookHTTPServer.SetPort(AValue: UInt16);
  671. begin
  672. if not FStreamedActive then
  673. CheckInactive;
  674. FPort := AValue;
  675. end;
  676. procedure TBrookHTTPServer.SetPostBufferSize(AValue: NativeUInt);
  677. begin
  678. if not FStreamedActive then
  679. CheckInactive;
  680. FPostBufferSize := AValue;
  681. end;
  682. procedure TBrookHTTPServer.SetConnectionLimit(AValue: Cardinal);
  683. begin
  684. if not FStreamedActive then
  685. CheckInactive;
  686. FConnectionLimit := AValue;
  687. end;
  688. procedure TBrookHTTPServer.SetConnectionTimeout(AValue: Cardinal);
  689. begin
  690. if not FStreamedActive then
  691. CheckInactive;
  692. FConnectionTimeout := AValue;
  693. end;
  694. procedure TBrookHTTPServer.SetPayloadLimit(AValue: NativeUInt);
  695. begin
  696. if not FStreamedActive then
  697. CheckInactive;
  698. FPayloadLimit := AValue;
  699. end;
  700. procedure TBrookHTTPServer.SetLocker(AValue: TBrookLocker);
  701. begin
  702. if FLocker = AValue then
  703. Exit;
  704. if Assigned(AValue) then
  705. FLocker.Active := AValue.Active
  706. else
  707. FLocker.Active := False;
  708. end;
  709. procedure TBrookHTTPServer.SetSecurity(AValue: TBrookHTTPServerSecurity);
  710. begin
  711. if FSecurity = AValue then
  712. Exit;
  713. if Assigned(AValue) then
  714. FSecurity.Assign(AValue)
  715. else
  716. FSecurity.Clear;
  717. end;
  718. procedure TBrookHTTPServer.SetUploadsLimit(AValue: UInt64);
  719. begin
  720. if not FStreamedActive then
  721. CheckInactive;
  722. FUploadsLimit := AValue;
  723. end;
  724. procedure TBrookHTTPServer.SetThreaded(AValue: Boolean);
  725. begin
  726. if not FStreamedActive then
  727. CheckInactive;
  728. FThreaded := AValue;
  729. if FThreaded then
  730. begin
  731. System.IsMultiThread := True;
  732. FLocker.Active := False;
  733. end;
  734. end;
  735. procedure TBrookHTTPServer.SetThreadPoolSize(AValue: Cardinal);
  736. begin
  737. if not FStreamedActive then
  738. CheckInactive;
  739. FThreadPoolSize := AValue;
  740. if FThreadPoolSize > 0 then
  741. System.IsMultiThread := True;
  742. end;
  743. procedure TBrookHTTPServer.SetUploadsDir(const AValue: string);
  744. begin
  745. if not FStreamedActive then
  746. CheckInactive;
  747. FUploadsDir := AValue;
  748. end;
  749. function TBrookHTTPServer.IsConnectionLimitStored: Boolean;
  750. begin
  751. Result := FConnectionLimit > 0;
  752. end;
  753. function TBrookHTTPServer.IsConnectionTimeoutStored: Boolean;
  754. begin
  755. Result := FConnectionTimeout > 0;
  756. end;
  757. function TBrookHTTPServer.IsNoFaviconStored: Boolean;
  758. begin
  759. Result := FNoFavicon;
  760. end;
  761. function TBrookHTTPServer.IsPayloadLimitStored: Boolean;
  762. begin
  763. Result := FPayloadLimit <> BROOK_PAYLOAD_LIMIT;
  764. end;
  765. function TBrookHTTPServer.IsUploadsLimitStored: Boolean;
  766. begin
  767. Result := FUploadsLimit <> BROOK_UPLOADS_LIMIT;
  768. end;
  769. function TBrookHTTPServer.IsActiveStored: Boolean;
  770. begin
  771. Result := FActive;
  772. end;
  773. function TBrookHTTPServer.GetPort: UInt16;
  774. begin
  775. if FActive and not (csDesigning in ComponentState) then
  776. begin
  777. SgLib.Check;
  778. FPort := sg_httpsrv_port(FHandle);
  779. end;
  780. Result := FPort;
  781. end;
  782. function TBrookHTTPServer.GetThreaded: Boolean;
  783. begin
  784. if FActive and not (csDesigning in ComponentState) then
  785. begin
  786. SgLib.Check;
  787. FThreaded := sg_httpsrv_is_threaded(FHandle);
  788. end;
  789. Result := FThreaded;
  790. end;
  791. function TBrookHTTPServer.GetUploadsDir: string;
  792. begin
  793. if FActive and not (csDesigning in ComponentState) then
  794. begin
  795. SgLib.Check;
  796. FUploadsDir := TMarshal.ToString(sg_httpsrv_upld_dir(FHandle));
  797. end;
  798. Result := FUploadsDir;
  799. end;
  800. function TBrookHTTPServer.GetPostBufferSize: NativeUInt;
  801. begin
  802. if FActive and not (csDesigning in ComponentState) then
  803. begin
  804. SgLib.Check;
  805. FPostBufferSize := sg_httpsrv_post_buf_size(FHandle);
  806. end;
  807. Result := FPostBufferSize;
  808. end;
  809. function TBrookHTTPServer.GetPayloadLimit: NativeUInt;
  810. begin
  811. if FActive and not (csDesigning in ComponentState) then
  812. begin
  813. SgLib.Check;
  814. FPayloadLimit := sg_httpsrv_payld_limit(FHandle);
  815. end;
  816. Result := FPayloadLimit;
  817. end;
  818. function TBrookHTTPServer.GetUploadsLimit: UInt64;
  819. begin
  820. if FActive and not (csDesigning in ComponentState) then
  821. begin
  822. SgLib.Check;
  823. FUploadsLimit := sg_httpsrv_uplds_limit(FHandle);
  824. end;
  825. Result := FUploadsLimit;
  826. end;
  827. function TBrookHTTPServer.GetThreadPoolSize: Cardinal;
  828. begin
  829. if FActive and not (csDesigning in ComponentState) then
  830. begin
  831. SgLib.Check;
  832. FThreadPoolSize := sg_httpsrv_thr_pool_size(FHandle);
  833. end;
  834. Result := FThreadPoolSize;
  835. end;
  836. function TBrookHTTPServer.GetConnectionTimeout: Cardinal;
  837. begin
  838. if FActive and not (csDesigning in ComponentState) then
  839. begin
  840. SgLib.Check;
  841. FConnectionTimeout := sg_httpsrv_con_timeout(FHandle);
  842. end;
  843. Result := FConnectionTimeout;
  844. end;
  845. function TBrookHTTPServer.GetConnectionLimit: Cardinal;
  846. begin
  847. if FActive and not (csDesigning in ComponentState) then
  848. begin
  849. SgLib.Check;
  850. FConnectionLimit := sg_httpsrv_con_limit(FHandle);
  851. end;
  852. Result := FConnectionLimit;
  853. end;
  854. function TBrookHTTPServer.IsAuthenticatedStored: Boolean;
  855. begin
  856. Result := FAuthenticated;
  857. end;
  858. function TBrookHTTPServer.IsPortStored: Boolean;
  859. begin
  860. Result := FPort <> 0;
  861. end;
  862. function TBrookHTTPServer.IsPostBufferSizeStored: Boolean;
  863. begin
  864. Result := FPostBufferSize <> BROOK_POST_BUFFER_SIZE;
  865. end;
  866. function TBrookHTTPServer.IsThreadedStored: Boolean;
  867. begin
  868. Result := FThreaded;
  869. end;
  870. function TBrookHTTPServer.IsThreadPoolSizeStored: Boolean;
  871. begin
  872. Result := FThreadPoolSize > 0;
  873. end;
  874. function TBrookHTTPServer.IsUploadsDirStored: Boolean;
  875. begin
  876. Result := not FUploadsDir.IsEmpty;
  877. end;
  878. procedure TBrookHTTPServer.SetAuthenticated(AValue: Boolean);
  879. begin
  880. if not FStreamedActive then
  881. CheckInactive;
  882. if AValue = FAuthenticated then
  883. Exit;
  884. if AValue and (csReading in ComponentState) then
  885. FStreamedAuthenticated := True;
  886. FAuthenticated := AValue;
  887. end;
  888. procedure TBrookHTTPServer.SetActive(AValue: Boolean);
  889. begin
  890. if AValue = FActive then
  891. Exit;
  892. if csDesigning in ComponentState then
  893. begin
  894. if not (csLoading in ComponentState) then
  895. SgLib.Check;
  896. FActive := AValue;
  897. end
  898. else
  899. if AValue then
  900. begin
  901. if csReading in ComponentState then
  902. FStreamedActive := True
  903. else
  904. DoOpen;
  905. end
  906. else
  907. DoClose;
  908. end;
  909. procedure TBrookHTTPServer.DoOpen;
  910. var
  911. M: TMarshaller;
  912. begin
  913. if Assigned(FHandle) then
  914. Exit;
  915. SgLib.Check;
  916. InternalCreateServerHandle;
  917. if not FUploadsDir.IsEmpty then
  918. InternalCheckServerOption(sg_httpsrv_set_upld_dir(FHandle,
  919. M.ToCString(FUploadsDir)));
  920. if FPostBufferSize > 0 then
  921. InternalCheckServerOption(sg_httpsrv_set_post_buf_size(FHandle,
  922. FPostBufferSize));
  923. if FPayloadLimit > 0 then
  924. InternalCheckServerOption(sg_httpsrv_set_payld_limit(FHandle,
  925. FPayloadLimit));
  926. if FUploadsLimit > 0 then
  927. InternalCheckServerOption(sg_httpsrv_set_uplds_limit(FHandle,
  928. FUploadsLimit));
  929. if FThreadPoolSize > 0 then
  930. InternalCheckServerOption(sg_httpsrv_set_thr_pool_size(FHandle,
  931. FThreadPoolSize));
  932. if FConnectionTimeout > 0 then
  933. InternalCheckServerOption(sg_httpsrv_set_con_timeout(FHandle,
  934. FConnectionTimeout));
  935. if FConnectionLimit > 0 then
  936. InternalCheckServerOption(sg_httpsrv_set_con_limit(FHandle,
  937. FConnectionLimit));
  938. InternalCheckServerOption(sg_httpsrv_set_cli_cb(FHandle,
  939. DoClientConnectionCallback, Self));
  940. if FSecurity.Active then
  941. begin
  942. FSecurity.Validate;
  943. if not Assigned(sg_httpsrv_tls_listen2) then
  944. raise ENotSupportedException.Create(SBrookTLSNotAvailable);
  945. FActive := sg_httpsrv_tls_listen2(FHandle,
  946. M.ToCNullableString(FSecurity.PrivateKey),
  947. M.ToCNullableString(FSecurity.PrivatePassword),
  948. M.ToCNullableString(FSecurity.Certificate),
  949. M.ToCNullableString(FSecurity.Trust),
  950. M.ToCNullableString(FSecurity.DHParams), FPort, FThreaded);
  951. end
  952. else
  953. FActive := sg_httpsrv_listen(FHandle, FPort, FThreaded);
  954. if not FActive then
  955. InternalFreeServerHandle
  956. else
  957. if Assigned(FOnStart) then
  958. FOnStart(Self);
  959. end;
  960. procedure TBrookHTTPServer.DoClose;
  961. begin
  962. if not Assigned(FHandle) then
  963. Exit;
  964. SgLib.Check;
  965. InternalShutdownServer;
  966. InternalFreeServerHandle;
  967. FActive := Assigned(FHandle);
  968. if Assigned(FOnStop) then
  969. FOnStop(Self);
  970. end;
  971. procedure TBrookHTTPServer.Open;
  972. begin
  973. SetActive(True);
  974. end;
  975. procedure TBrookHTTPServer.Close;
  976. begin
  977. SetActive(False);
  978. end;
  979. end.