/mORMot/SQLite3/mORMotHttpServer.pas

https://bitbucket.org/sas_team/sas.requires · Pascal · 1125 lines · 617 code · 55 blank · 453 comment · 98 complexity · 27e304fefa0047ae83af31a566bb791e MD5 · raw file

  1. /// HTTP/1.1 RESTFUL JSON Server classes for mORMot
  2. // - this unit is a part of the freeware Synopse mORMot framework,
  3. // licensed under a MPL/GPL/LGPL tri-license; version 1.18
  4. unit mORMotHttpServer;
  5. {
  6. This file is part of Synopse mORMot framework.
  7. Synopse mORMot framework. Copyright (C) 2016 Arnaud Bouchez
  8. Synopse Informatique - http://synopse.info
  9. *** BEGIN LICENSE BLOCK *****
  10. Version: MPL 1.1/GPL 2.0/LGPL 2.1
  11. The contents of this file are subject to the Mozilla Public License Version
  12. 1.1 (the "License"); you may not use this file except in compliance with
  13. the License. You may obtain a copy of the License at
  14. http://www.mozilla.org/MPL
  15. Software distributed under the License is distributed on an "AS IS" basis,
  16. WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  17. for the specific language governing rights and limitations under the License.
  18. The Original Code is Synopse mORMot framework.
  19. The Initial Developer of the Original Code is Arnaud Bouchez.
  20. Portions created by the Initial Developer are Copyright (C) 2016
  21. the Initial Developer. All Rights Reserved.
  22. Contributor(s):
  23. - DigDiver (for HTTPS support)
  24. - cheemeng
  25. Alternatively, the contents of this file may be used under the terms of
  26. either the GNU General Public License Version 2 or later (the "GPL"), or
  27. the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  28. in which case the provisions of the GPL or the LGPL are applicable instead
  29. of those above. If you wish to allow use of your version of this file only
  30. under the terms of either the GPL or the LGPL, and not to allow others to
  31. use your version of this file under the terms of the MPL, indicate your
  32. decision by deleting the provisions above and replace them with the notice
  33. and other provisions required by the GPL or the LGPL. If you do not delete
  34. the provisions above, a recipient may use your version of this file under
  35. the terms of any one of the MPL, the GPL or the LGPL.
  36. ***** END LICENSE BLOCK *****
  37. HTTP/1.1 RESTFUL JSON Client/Server for mORMot
  38. ************************************************
  39. - use internaly the JSON format for content communication
  40. - can be called by TSQLHttpClient class from direct Delphi clients
  41. (see mORMotHttpClient unit)
  42. - can be called by any JSON-aware AJAX application
  43. - can optionaly compress the returned data to optimize Internet bandwidth
  44. - speed is very high: more than 20MB/sec R/W localy on a 1.8GHz Sempron,
  45. i.e. 400Mb/sec of duplex raw IP data, with about 200 µs only elapsed
  46. by request (direct call is 50 µs, so bottle neck is the Win32 API),
  47. i.e. 5000 requests per second, with 113 result rows (i.e. 4803 bytes
  48. of JSON data each)... try to find a faster JSON HTTP server! ;)
  49. Initial version: 2009 May, by Arnaud Bouchez
  50. Version 1.1
  51. - code rewrite for FPC and Delphi 2009/2010 compilation
  52. Version 1.3 - January 22, 2010
  53. - some small fixes and multi-compiler enhancements
  54. Version 1.4 - February 8, 2010
  55. - whole Synopse SQLite3 database framework released under the GNU Lesser
  56. General Public License version 3, instead of generic "Public Domain"
  57. - HTTP/1.1 RESTFUL JSON Client and Server split into two units
  58. (SQLite3HttpClient and SQLite3HttpServer)
  59. Version 1.5 - February 22, 2010
  60. - by default, the SQlite3 unit is now not included, in order to save
  61. some space
  62. Version 1.8
  63. - includes Unitary Testing class and functions
  64. - allows content-type changing for GET blob fields
  65. Version 1.12
  66. - TSQLHttpServer now handle multiple TSQLRestServer instances
  67. per one server (dispatching requests via the Root URI used)
  68. - new AddServer method, to register a TSQLRestServer after launch
  69. - new TSQLRestServer.OnlyJSONRequests property
  70. Version 1.13
  71. - can now use fast http.sys kernel-mode server (THttpApiServer) if
  72. available, and our pure Delphi THttpServer on default
  73. - now can compress its content using deflate or faster SynLZ algorithm
  74. - by default, will handle SynLZ compression for TSQLHttpClient
  75. - can make TCP/IP stream not HTTP compliant (for security visions)
  76. - TSQLHttpServer.Request now uses the new THttpServerGeneric.Request
  77. virtual abstract method prototype to handle THttpApiServer
  78. Version 1.16
  79. - added optional aRestAccessRights parameter in TSQLHttpServer.AddServer
  80. to override the default HTTP_DEFAULT_ACCESS_RIGHTS settings
  81. - added ServerThreadPoolCount parameter to TSQLHttpServer.Create()
  82. constructor, set by default to 32 - will speed up process of slow
  83. requests (e.g. a POST with some huge data transmitted at slow rate)
  84. - fixed error in case of URI similar to 'root?session_signature=...'
  85. - fixed incorect thread count in TSQLHttpServer.Create
  86. - regression tests are now extracted from this unit, in order to allow
  87. construction of a TSQLHttpServer instance without the need
  88. of linking the SQLite3 engine to the executable
  89. Version 1.17
  90. - made URI check case-insensitive (as for official RFC)
  91. - TSQLHttpServer will now call virtual TSQLRestServer.EndCurrentThread
  92. method in each of its terminating threads, to release any thread-specific
  93. resources (for instance, external connections in SQlite3DB)
  94. Version 1.18
  95. - renamed SQLite3HttpServer.pas unit to mORMotHttpServer.pas
  96. - classes TSQLHttpServer* renamed as TSQLHttpServer*
  97. - added TSQLHttpServer.RemoveServer() and Shutdown methods
  98. - added TSQLHttpServer.Port and DomainName properties
  99. - added TSQLHttpServer.AccessControlAllowOrigin property to handle
  100. cross-site AJAX requests via cross-origin resource sharing (CORS)
  101. - added TSQLHttpServer.RedirectServerRootUriForExactCase to fix
  102. URIs on the fly for case sensitivity
  103. - TSQLHttpServer now handles sub-domains generic matching (via
  104. TSQLModel.URIMatch call) at database model level (e.g. you can set
  105. root='/root/sub1' URIs)
  106. - added TSQLHttpServer.DomainHostRedirect() method for virtual-host
  107. redirection of Internet domains or sub-domains
  108. - declared TSQLHttpServer.Request method as virtual, to allow easiest
  109. customization, like direct file sending to the clients
  110. - added TSQLHttpServerOptions parameter to TSQLHttpServer.Create(),
  111. allowing optional auto-registration of the URI to http.sys internals
  112. - added aHttpServerSecurity: TSQLHttpServerSecurity parameter to
  113. TSQLHttpServer.Create(), allowing HTTPS secure content publishing, when
  114. using the http.sys kind of server, or our proprietary SHA-256 /
  115. AES-256-CTR encryption identified as "ACCEPT-ENCODING: synshaaes"
  116. - added optional aAdditionalURL parameter to TSQLHttpServer.Create(), to
  117. be used e.g. to registry an URI to server static file content in addition
  118. to TSQLRestServer instances - need to override TSQLHttpServer.Request()
  119. - added optional parameter to TSQLHttpServer.Create(), to specify a
  120. name for the THttpApiServer HTTP queue
  121. - COMPRESSDEFLATE conditional will use gzip (and not deflate/zip)
  122. - added TSQLHTTPRemoteLogServer class for easy remote log serving
  123. - ensure TSQLHttpServer.AddServer() will handle useHttpApiRegisteringURI
  124. - added TSQLHttpServer.RootRedirectToURI() method for root URI redirection
  125. - declared TSQLHttpServer.HttpThreadStart/HttpThreadTerminate as virtual
  126. - allow TSQLHttpServer.Create() without any associated TSQLRestServer
  127. - allow to specify the binding server address for sockets ('1.2.3.4:1234')
  128. - implement asynchronous interface callbacks using WebSockets
  129. }
  130. interface
  131. {$define COMPRESSSYNLZ}
  132. { if defined, will use SynLZ for content compression
  133. - SynLZ is much faster than deflate/zip, so is preferred
  134. - can be set global for Client and Server applications
  135. - with SynLZ, the 440 KB JSON for TTestClientServerAccess._TSQLHttpClient
  136. is compressed into 106 KB with no speed penalty (it's even a bit faster)
  137. whereas deflate, even with its level set to 1 (fastest), is 25 % slower
  138. - TSQLHttpClientGeneric.Compression shall contain hcSynLZ to handle it }
  139. {$define COMPRESSDEFLATE}
  140. { if defined, will use gzip (and not deflate/zip) for content compression
  141. - can be set global for Client and Server applications
  142. - deflate/zip is just broken between browsers and client, and should be
  143. avoided: see http://stackoverflow.com/a/9186091/458259
  144. - SynLZ is faster but only known by Delphi clients: you can enable deflate
  145. when the server is connected an AJAX application (not defined by default)
  146. - if you define both COMPRESSSYNLZ and COMPRESSDEFLATE, the server will use
  147. SynLZ if available, and deflate if not called from a Delphi client
  148. - TSQLHttpClientGeneric.Compression shall contain hcDeflate to handle it }
  149. {.$define USETCPPREFIX}
  150. { if defined, a prefix will be added to the TCP/IP stream so that it won't be
  151. valid HTTP content any more: it could increase the client/server speed with
  152. some anti-virus software, but the remote access won't work any more with
  153. Internet Browsers nor AJAX applications
  154. - will work only with our THttpServer pure Delphi code, of course
  155. - not defined by default - should be set globally to the project conditionals,
  156. to be defined in both mORMotHttpClient and mORMotHttpServer units }
  157. {$I Synopse.inc} // define HASINLINE WITHLOG USETHREADPOOL ONLYUSEHTTPSOCKET
  158. uses
  159. {$ifdef MSWINDOWS}
  160. Windows,
  161. {$endif}
  162. {$ifdef KYLIX3}
  163. Types,
  164. LibC,
  165. {$endif}
  166. SysUtils,
  167. Classes,
  168. {$ifdef COMPRESSDEFLATE}
  169. SynZip,
  170. {$endif}
  171. {$ifdef COMPRESSSYNLZ}
  172. SynLZ,
  173. {$endif}
  174. SynCrtSock,
  175. SynBidirSock, // for WebSockets
  176. SynCrypto, // for CompressShaAes()
  177. SynCommons,
  178. SynLog,
  179. mORMot;
  180. type
  181. /// exception raised in case of a HTTP Server error
  182. EHttpServerException = class(ECommunicationException);
  183. /// available running options for TSQLHttpServer.Create() constructor
  184. // - useHttpApi to use kernel-mode HTTP.SYS server (THttpApiServer) with an
  185. // already registered URI (default way, similar to IIS/WCF security policy
  186. // as specified by Microsoft) - you would need to register the URI by hand,
  187. // e.g. in the Setup program, via code similar to this one:
  188. // ! THttpApiServer.AddUrlAuthorize('root','888',false,'+'))
  189. // - useHttpApiRegisteringURI will first registry the given URI, then use
  190. // kernel-mode HTTP.SYS server (THttpApiServer) - will need Administrator
  191. // execution rights at least one time (e.g. during setup); note that if
  192. // the URI is already registered, the server will still be launched, even if
  193. // the program does not run as Administrator - it is therefore sufficient
  194. // to run such a program once as Administrator to register the URI, when this
  195. // useHttpApiRegisteringURI option is set
  196. // - useHttpSocket will use the standard Sockets library (i.e. socket-based
  197. // THttpServer) - it will trigger the Windows firewall popup UAC window at
  198. // first execution
  199. // - useBidirSocket will use the standard Sockets library but via the
  200. // TWebSocketServerRest class, allowing HTTP connection upgrade to the
  201. // WebSockets protocol, allowing immediate event callbacks in addition to the
  202. // standard RESTful mode
  203. // - the first item should be the preferred one (see HTTP_DEFAULT_MODE)
  204. TSQLHttpServerOptions =
  205. ({$ifndef ONLYUSEHTTPSOCKET}useHttpApi, useHttpApiRegisteringURI, {$endif}
  206. useHttpSocket, useBidirSocket);
  207. /// available security options for TSQLHttpServer.Create() constructor
  208. // - default secNone will use plain HTTP connection
  209. // - secSSL will use HTTPS secure connection
  210. // - secSynShaAes will use our proprietary SHA-256 / AES-256-CTR encryption
  211. // identified as 'synshaaes' as ACCEPT-ENCODING: header parameter
  212. TSQLHttpServerSecurity =
  213. (secNone, secSSL, secSynShaAes);
  214. const
  215. /// the default access rights used by the HTTP server if none is specified
  216. HTTP_DEFAULT_ACCESS_RIGHTS: PSQLAccessRights = @SUPERVISOR_ACCESS_RIGHTS;
  217. /// the kind of HTTP server to be used by default
  218. // - will define the best available server class, depending on the platform
  219. HTTP_DEFAULT_MODE = {$ifdef ONLYUSEHTTPSOCKET}useHttpSocket{$else}useHttpApiRegisteringURI{$endif};
  220. type
  221. /// HTTP/1.1 RESTFUL JSON mORMot Server class
  222. // - this server is multi-threaded and not blocking
  223. // - under Windows, it will first try to use fastest http.sys kernel-mode
  224. // server (i.e. create a THttpApiServer instance); it should work OK under XP
  225. // or WS 2K3 - but you need to have administrator rights under Vista or Seven:
  226. // if http.sys fails to initialize, it will use the socket-based THttpServer;
  227. // a solution is to call the THttpApiServer.AddUrlAuthorize class method during
  228. // program setup for the desired port, in order to allow it for every user
  229. // - under Linux, only THttpServer is available
  230. // - you can specify useBidirSocket kind of server (i.e. TWebSocketServerRest)
  231. // if you want the HTTP protocol connection to be upgraded to a WebSockets
  232. // mode, to allow immediate callbacks from the server to the client
  233. // - just create it and it will serve SQL statements as UTF-8 JSON
  234. // - for a true AJAX server, expanded data is prefered - your code may contain:
  235. // ! DBServer.NoAJAXJSON := false;
  236. TSQLHttpServer = class
  237. protected
  238. fOnlyJSONRequests: boolean;
  239. fHttpServer: THttpServerGeneric;
  240. fPort, fDomainName: AnsiString;
  241. fPublicAddress, fPublicPort: RawUTF8;
  242. /// internal servers to compute responses
  243. fDBServers: array of record
  244. Server: TSQLRestServer;
  245. RestAccessRights: PSQLAccessRights;
  246. Security: TSQLHttpServerSecurity;
  247. end;
  248. fHosts: TSynNameValue;
  249. fAccessControlAllowOrigin: RawUTF8;
  250. fAccessControlAllowOriginHeader: RawUTF8;
  251. fRootRedirectToURI: array[boolean] of RawUTF8;
  252. fRedirectServerRootUriForExactCase: boolean;
  253. fHttpServerKind: TSQLHttpServerOptions;
  254. fLog: TSynLogClass;
  255. procedure SetAccessControlAllowOrigin(const Value: RawUTF8);
  256. // assigned to fHttpServer.OnHttpThreadStart/Terminate e.g. to handle connections
  257. procedure HttpThreadStart(Sender: TThread); virtual;
  258. procedure HttpThreadTerminate(Sender: TThread); virtual;
  259. /// implement the server response - must be thread-safe
  260. function Request(Ctxt: THttpServerRequest): cardinal; virtual;
  261. function GetDBServerCount: integer; {$ifdef HASINLINE}inline;{$endif}
  262. function GetDBServer(Index: Integer): TSQLRestServer; {$ifdef HASINLINE}inline;{$endif}
  263. procedure SetDBServerAccessRight(Index: integer; Value: PSQLAccessRights);
  264. procedure SetDBServer(aIndex: integer; aServer: TSQLRestServer;
  265. aSecurity: TSQLHttpServerSecurity; aRestAccessRights: PSQLAccessRights);
  266. function GetDBServerNames: RawUTF8;
  267. function HttpApiAddUri(const aRoot,aDomainName: RawByteString;
  268. aSecurity: TSQLHttpServerSecurity; aRegisterURI,aRaiseExceptionOnError: boolean): RawUTF8;
  269. function NotifyCallback(aSender: TSQLRestServer;
  270. const aInterfaceDotMethodName,aParams: RawUTF8;
  271. aConnectionID: Int64; aFakeCallID: integer;
  272. aResult, aErrorMsg: PRawUTF8): boolean;
  273. public
  274. /// create a Server instance, binded and listening on a TCP port to HTTP requests
  275. // - raise a EHttpServer exception if binding failed
  276. // - specify one or more TSQLRestServer server class to be used: each
  277. // class must have an unique Model.Root value, to identify which TSQLRestServer
  278. // instance must handle a particular request from its URI
  279. // - port is an AnsiString, as expected by the WinSock API - in case of
  280. // useHttpSocket or useBidirSocket kind of server, you should specify the
  281. // public server address to bind to: e.g. '1.2.3.4:1234' - even for http.sys,
  282. // the public address could be used e.g. for TSQLRestServer.SetPublicURI()
  283. // - aDomainName is the URLprefix to be used for HttpAddUrl API call:
  284. // it could be either a fully qualified case-insensitive domain name
  285. // an IPv4 or IPv6 literal string, or a wildcard ('+' will bound
  286. // to all domain names for the specified port, '*' will accept the request
  287. // when no other listening hostnames match the request for that port) - this
  288. // parameter is ignored by the TSQLHttpApiServer instance
  289. // - aHttpServerKind defines how the HTTP server itself will be implemented:
  290. // it will use by default optimized kernel-based http.sys server (useHttpApi),
  291. // optionally registering the URI (useHttpApiRegisteringURI) if needed,
  292. // or using the standard Sockets library (useHttpSocket), possibly in its
  293. // WebSockets-friendly version (useBidirSocket - you shoud call the
  294. // WebSocketsEnable method to initialize the available protocols)
  295. // - by default, the PSQLAccessRights will be set to nil
  296. // - the ServerThreadPoolCount parameter will set the number of threads
  297. // to be initialized to handle incoming connections (default is 32, which
  298. // may be sufficient for most cases, maximum is 256)
  299. // - the aHttpServerSecurity can be set to secSSL to initialize a HTTPS
  300. // instance (after proper certificate installation as explained in the SAD
  301. // pdf), or to secSynShaAes if you want our proprietary SHA-256 /
  302. // AES-256-CTR encryption identified as "ACCEPT-ENCODING: synshaaes"
  303. // - optional aAdditionalURL parameter can be used e.g. to registry an URI
  304. // to server static file content, by overriding TSQLHttpServer.Request
  305. // - for THttpApiServer, you can specify an optional name for the HTTP queue
  306. constructor Create(const aPort: AnsiString;
  307. const aServers: array of TSQLRestServer; const aDomainName: AnsiString='+';
  308. aHttpServerKind: TSQLHttpServerOptions=HTTP_DEFAULT_MODE; ServerThreadPoolCount: Integer=32;
  309. aHttpServerSecurity: TSQLHttpServerSecurity=secNone;
  310. const aAdditionalURL: AnsiString=''; const aQueueName: SynUnicode=''); reintroduce; overload;
  311. /// create a Server instance, binded and listening on a TCP port to HTTP requests
  312. // - raise a EHttpServer exception if binding failed
  313. // - specify one TSQLRestServer server class to be used
  314. // - port is an AnsiString, as expected by the WinSock API - in case of
  315. // useHttpSocket or useBidirSocket kind of server, you can specify the
  316. // public server address to bind to: e.g. '1.2.3.4:1234' - even for http.sys,
  317. // the public address could be used e.g. for TSQLRestServer.SetPublicURI()
  318. // - aDomainName is the URLprefix to be used for HttpAddUrl API call
  319. // - the aHttpServerSecurity can be set to secSSL to initialize a HTTPS
  320. // instance (after proper certificate installation as explained in the SAD
  321. // pdf), or to secSynShaAes if you want our proprietary SHA-256 /
  322. // AES-256-CTR encryption identified as "ACCEPT-ENCODING: synshaaes"
  323. // - optional aAdditionalURL parameter can be used e.g. to registry an URI
  324. // to server static file content, by overriding TSQLHttpServer.Request
  325. // - for THttpApiServer, you can specify an optional name for the HTTP queue
  326. constructor Create(const aPort: AnsiString; aServer: TSQLRestServer;
  327. const aDomainName: AnsiString='+';
  328. aHttpServerKind: TSQLHttpServerOptions=HTTP_DEFAULT_MODE; aRestAccessRights: PSQLAccessRights=nil;
  329. ServerThreadPoolCount: Integer=32; aHttpServerSecurity: TSQLHttpServerSecurity=secNone;
  330. const aAdditionalURL: AnsiString=''; const aQueueName: SynUnicode=''); reintroduce; overload;
  331. /// create a Server instance, binded and listening on a TCP port to HTTP requests
  332. // - raise a EHttpServer exception if binding failed
  333. // - specify one TSQLRestServer instance to be published, and the associated
  334. // transmission definition; other parameters would be the standard one
  335. // - only the supplied aDefinition.Authentication will be defined
  336. // - under Windows, will use http.sys with automatic URI registration, unless
  337. // aDefinition.WebSocketPassword is set, and then binary WebSockets would
  338. // be expected with the corresponding encryption
  339. constructor Create(aServer: TSQLRestServer; aDefinition: TSQLHttpServerDefinition); reintroduce; overload;
  340. /// release all memory, internal mORMot server and HTTP handlers
  341. destructor Destroy; override;
  342. /// you can call this method to prepare the HTTP server for shutting down
  343. // - it will call all associated TSQLRestServer.Shutdown methods
  344. // - note that Destroy won't call this method on its own, since the
  345. // TSQLRestServer instances may have a life-time uncoupled from HTTP process
  346. procedure Shutdown;
  347. /// try to register another TSQLRestServer instance to the HTTP server
  348. // - each TSQLRestServer class must have an unique Model.Root value, to
  349. // identify which instance must handle a particular request from its URI
  350. // - an optional aRestAccessRights parameter is available to override the
  351. // default HTTP_DEFAULT_ACCESS_RIGHTS access right setting - but you shall
  352. // better rely on the authentication feature included in the framework
  353. // - the aHttpServerSecurity can be set to secSSL to initialize a HTTPS
  354. // instance (after proper certificate installation as explained in the SAD
  355. // pdf), or to secSynShaAes if you want our proprietary SHA-256 /
  356. // AES-256-CTR encryption identified as "ACCEPT-ENCODING: synshaaes"
  357. // - return true on success, false on error (e.g. duplicated Root value)
  358. function AddServer(aServer: TSQLRestServer; aRestAccessRights: PSQLAccessRights=nil;
  359. aHttpServerSecurity: TSQLHttpServerSecurity=secNone): boolean;
  360. /// un-register a TSQLRestServer from the HTTP server
  361. // - each TSQLRestServer class must have an unique Model.Root value, to
  362. // identify which instance must handle a particular request from its URI
  363. // - return true on success, false on error (e.g. specified server not found)
  364. function RemoveServer(aServer: TSQLRestServer): boolean;
  365. /// register a domain name to be redirected to a given Model.Root
  366. // - i.e. can be used to support some kind of virtual hosting
  367. // - by default, the URI would be used to identify which TSQLRestServer
  368. // instance to use, and the incoming HOST value would just be ignored
  369. // - you can specify here domain names which would be checked against
  370. // the incoming HOST header, to redirect to a given URI, as such:
  371. // ! DomainHostRedirect('project1.com','root1');
  372. // ! DomainHostRedirect('project2.com','root2');
  373. // ! DomainHostRedirect('blog.project2.com','root2/blog');
  374. // for the last entry, you may have for instance initialized a MVC web
  375. // server on the 'blog' sub-URI of the 'root2' TSQLRestServer via:
  376. // !constructor TMyMVCApplication.Create(aRestModel: TSQLRest; aInterface: PTypeInfo);
  377. // ! ...
  378. // ! fMainRunner := TMVCRunOnRestServer.Create(self,nil,'blog');
  379. // ! ...
  380. // - if aURI='' is given, the corresponding host redirection will be disabled
  381. procedure DomainHostRedirect(const aDomain,aURI: RawUTF8);
  382. /// allow to temporarly redirect ip:port root URI to a given sub-URI
  383. // - by default, only sub-URI, as defined by TSQLRestServer.Model.Root, are
  384. // registered - you can define here a sub-URI to reach when the main server
  385. // is directly accessed from a browser, e.g. localhost:port will redirect to
  386. // localhost:port/RedirectedURI
  387. // - for http.sys server, would try to register '/' if aRegisterURI is TRUE
  388. // - by default, will redirect http://localhost:port unless you set
  389. // aHttpServerSecurity=secSSL so that it would redirect https://localhost:port
  390. procedure RootRedirectToURI(const aRedirectedURI: RawUTF8;
  391. aRegisterURI: boolean=true; aHttps: boolean=false);
  392. /// defines the WebSockets protocols to be used for useBidirSocket
  393. // - i.e. 'synopsebinary' and optionally 'synopsejson' protocols
  394. // - if aWebSocketsURI is '', any URI would potentially upgrade; you can
  395. // specify an URI to limit the protocol upgrade to a single REST server
  396. // - TWebSocketProtocolBinary will always be registered by this method
  397. // - if the encryption key text is not '', TWebSocketProtocolBinary will
  398. // use AES-CFB 256 bits encryption
  399. // - if aWebSocketsAJAX is TRUE, it will also register TWebSocketProtocolJSON
  400. // so that AJAX applications would be able to connect to this server
  401. // - this method does nothing if the associated HttpServer class is not a
  402. // TWebSocketServerRest (i.e. this instance was not created as useBidirSocket)
  403. function WebSocketsEnable(const aWebSocketsURI, aWebSocketsEncryptionKey: RawUTF8;
  404. aWebSocketsAJAX: boolean=false; aWebSocketsCompressed: boolean=true): TWebSocketServerRest; overload;
  405. /// defines the useBidirSocket WebSockets protocol to be used for a REST server
  406. // - same as the overloaded WebSocketsEnable() method, but the URI will be
  407. // forced to match the aServer.Model.Root value, as expected on the client
  408. // side by TSQLHttpClientWebsockets.WebSocketsUpgrade()
  409. function WebSocketsEnable(aServer: TSQLRestServer;
  410. const aWebSocketsEncryptionKey: RawUTF8; aWebSocketsAJAX: boolean=false;
  411. aWebSocketsCompressed: boolean=true): TWebSocketServerRest; overload;
  412. /// the associated running HTTP server instance
  413. // - either THttpApiServer (available only under Windows), THttpServer or
  414. // TWebSocketServerRest (on any system)
  415. property HttpServer: THttpServerGeneric read fHttpServer;
  416. /// the TCP/IP (address and) port on which this server is listening to
  417. // - may contain the public server address to bind to: e.g. '1.2.3.4:1234'
  418. // - see PublicAddress and PublicPort properties if you want to get the
  419. // true IP port or address
  420. property Port: AnsiString read fPort;
  421. /// the TCP/IP public address on which this server is listening to
  422. // - equals e.g. '1.2.3.4' if Port = '1.2.3.4:1234'
  423. // - if Port does not contain an explicit address (e.g. '1234'), the current
  424. // computer host name would be assigned as PublicAddress
  425. property PublicAddress: RawUTF8 read fPublicAddress;
  426. /// the TCP/IP public port on which this server is listening to
  427. // - equals e.g. '1234' if Port = '1.2.3.4:1234'
  428. property PublicPort: RawUTF8 read fPublicPort;
  429. /// the URLprefix used for internal HttpAddUrl API call
  430. property DomainName: AnsiString read fDomainName;
  431. /// read-only access to the number of registered internal servers
  432. property DBServerCount: integer read GetDBServerCount;
  433. /// read-only access to all internal servers
  434. property DBServer[Index: integer]: TSQLRestServer read GetDBServer;
  435. /// write-only access to all internal servers access right
  436. // - can be used to override the default HTTP_DEFAULT_ACCESS_RIGHTS setting
  437. property DBServerAccessRight[Index: integer]: PSQLAccessRights write SetDBServerAccessRight;
  438. /// find the first instance of a registered REST server
  439. // - note that the same REST server may appear several times in this HTTP
  440. // server instance, e.g. with diverse security options
  441. function DBServerFind(aServer: TSQLRestServer): integer;
  442. /// set this property to TRUE if the server must only respond to
  443. // request of MIME type APPLICATION/JSON
  444. // - the default is false, in order to allow direct view of JSON from
  445. // any browser
  446. property OnlyJSONRequests: boolean read fOnlyJSONRequests write fOnlyJSONRequests;
  447. /// enable cross-origin resource sharing (CORS) for proper AJAX process
  448. // - see @https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS
  449. // - can be set e.g. to '*' to allow requests from any sites
  450. // - or specify an URI to be allowed as origin (e.g. 'http://foo.example')
  451. // - current implementation is pretty basic, and does not check the incoming
  452. // "Origin: " header value
  453. property AccessControlAllowOrigin: RawUTF8 read fAccessControlAllowOrigin write SetAccessControlAllowOrigin;
  454. /// enable redirectoin to fix any URI for a case-sensitive match of Model.Root
  455. // - by default, TSQLRestServer.Model.Root would be accepted with case
  456. // insensitivity; but it may induce errors for HTTP cookies, since they
  457. // are bound with '; Path=/ModelRoot', which is case-sensitive on the
  458. // browser side
  459. // - set this property to TRUE so that only exact case URI would be handled
  460. // by TSQLRestServer.URI(), and any case-sensitive URIs (e.g. /Root/... or
  461. // /ROOT/...) would be temporary redirected to Model.Root (e.g. /root/...)
  462. // via a HTTP 307 command
  463. property RedirectServerRootUriForExactCase: boolean
  464. read fRedirectServerRootUriForExactCase write fRedirectServerRootUriForExactCase;
  465. end;
  466. /// callback expected by TSQLHTTPRemoteLogServer to notify about a received log
  467. TRemoteLogReceivedOne = procedure(const Text: RawUTF8) of object;
  468. {$M+}
  469. /// limited HTTP server which is will receive remote log notifications
  470. // - this will create a simple in-memory mORMot server, which will trigger
  471. // a supplied callback when a remote log is received
  472. // - see TSQLHttpClientWinGeneric.CreateForRemoteLogging() for the client side
  473. // - used e.g. by the LogView tool
  474. TSQLHTTPRemoteLogServer = class(TSQLHttpServer)
  475. protected
  476. fServer: TSQLRestServerFullMemory;
  477. fEvent: TRemoteLogReceivedOne;
  478. public
  479. /// initialize the HTTP server and an internal mORMot server
  480. // - you can share several HTTP log servers on the same port, if you use
  481. // a dedicated root URI and use the http.sys server (which is the default)
  482. constructor Create(const aRoot: RawUTF8; aPort: integer;
  483. const aEvent: TRemoteLogReceivedOne);
  484. /// release the HTTP server and its internal mORMot server
  485. destructor Destroy; override;
  486. /// the associated mORMot server instance running with this HTTP server
  487. property Server: TSQLRestServerFullMemory read fServer;
  488. published
  489. /// this HTTP server will publish a 'RemoteLog' method-based service
  490. // - expecting PUT with text as body, at http://server/root/RemoteLog
  491. procedure RemoteLog(Ctxt: TSQLRestServerURIContext);
  492. end;
  493. {$M-}
  494. var
  495. /// a global hook variable, able to enhance WebSockets logging
  496. // - when a TSQLHttpServer is created from a TSQLHttpServerDefinition
  497. HttpServerFullWebSocketsLog: Boolean;
  498. function ToText(opt: TSQLHttpServerOptions): PShortString; overload;
  499. function ToText(sec: TSQLHttpServerSecurity): PShortString; overload;
  500. implementation
  501. function ToText(opt: TSQLHttpServerOptions): PShortString;
  502. begin
  503. result := GetEnumName(TypeInfo(TSQLHttpServerOptions),ord(opt));
  504. end;
  505. function ToText(sec: TSQLHttpServerSecurity): PShortString;
  506. begin
  507. result := GetEnumName(TypeInfo(TSQLHttpServerSecurity),ord(sec));
  508. end;
  509. { TSQLHttpServer }
  510. function TSQLHttpServer.AddServer(aServer: TSQLRestServer;
  511. aRestAccessRights: PSQLAccessRights; aHttpServerSecurity: TSQLHttpServerSecurity): boolean;
  512. var i,n: integer;
  513. begin
  514. result := False;
  515. if (self=nil) or (aServer=nil) or (aServer.Model=nil) then
  516. exit;
  517. fLog.Enter(self);
  518. try
  519. n := length(fDBServers);
  520. for i := 0 to n-1 do
  521. if (fDBServers[i].Server.Model.URIMatch(aServer.Model.Root)<>rmNoMatch) and
  522. (fDBServers[i].Security=aHttpServerSecurity) then
  523. exit; // register only once per URI Root address and per protocol
  524. {$ifndef ONLYUSEHTTPSOCKET}
  525. if fHttpServerKind in [useHttpApi,useHttpApiRegisteringURI] then
  526. if HttpApiAddUri(aServer.Model.Root,fDomainName,aHttpServerSecurity,
  527. fHttpServerKind=useHttpApiRegisteringURI,false)<>'' then
  528. exit;
  529. {$endif}
  530. SetLength(fDBServers,n+1);
  531. SetDBServer(n,aServer,aHttpServerSecurity,aRestAccessRights);
  532. fHttpServer.ProcessName := GetDBServerNames;
  533. result := true;
  534. finally
  535. fLog.Add.Log(sllHttp,'%.AddServer(%,Root=%,Port=%,Public=%:%)=%',
  536. [self,aServer,aServer.Model.Root,fPort,fPublicAddress,fPublicPort,
  537. BOOL_STR[result]],self);
  538. end;
  539. end;
  540. function TSQLHttpServer.DBServerFind(aServer: TSQLRestServer): integer;
  541. begin
  542. for result := 0 to Length(fDBServers)-1 do
  543. if fDBServers[result].Server=aServer then
  544. exit;
  545. result := -1;
  546. end;
  547. function TSQLHttpServer.RemoveServer(aServer: TSQLRestServer): boolean;
  548. var i,j,n: integer;
  549. begin
  550. result := False;
  551. if (self=nil) or (aServer=nil) or (aServer.Model=nil) then
  552. exit;
  553. fLog.Enter(self);
  554. try
  555. n := high(fDBServers);
  556. for i := n downto 0 do // may appear several times, with another Security
  557. if fDBServers[i].Server=aServer then begin
  558. {$ifndef ONLYUSEHTTPSOCKET}
  559. if fHttpServer.InheritsFrom(THttpApiServer) then
  560. if THttpApiServer(fHttpServer).RemoveUrl(aServer.Model.Root,fPublicPort,
  561. fDBServers[i].Security=secSSL,fDomainName)<>NO_ERROR then
  562. fLog.Add.Log(sllLastError,'%.RemoveUrl(%)',[self,aServer.Model.Root],self);
  563. {$endif}
  564. for j := i to n-1 do
  565. fDBServers[j] := fDBServers[j+1];
  566. SetLength(fDBServers,n);
  567. dec(n);
  568. aServer.OnNotifyCallback := nil;
  569. aServer.SetPublicURI('','');
  570. result := true; // don't break here: may appear with another Security
  571. end;
  572. finally
  573. fLog.Add.Log(sllHttp,'%.RemoveServer(Root=%)=%',
  574. [self,aServer.Model.Root,BOOL_STR[result]],self);
  575. end;
  576. end;
  577. procedure TSQLHttpServer.DomainHostRedirect(const aDomain,aURI: RawUTF8);
  578. begin
  579. if aURI='' then
  580. fHosts.Delete(aDomain) else
  581. fHosts.Add(aDomain,aURI);
  582. end;
  583. constructor TSQLHttpServer.Create(const aPort: AnsiString;
  584. const aServers: array of TSQLRestServer; const aDomainName: AnsiString;
  585. aHttpServerKind: TSQLHttpServerOptions; ServerThreadPoolCount: Integer;
  586. aHttpServerSecurity: TSQLHttpServerSecurity; const aAdditionalURL: AnsiString;
  587. const aQueueName: SynUnicode);
  588. var i,j: integer;
  589. ServersRoot: RawUTF8;
  590. ErrMsg: RawUTF8;
  591. begin
  592. {$ifdef WITHLOG} // this is the only place where we check for WITHLOG
  593. if high(aServers)<0 then
  594. fLog := TSQLLog else
  595. fLog := aServers[0].LogClass;
  596. fLog.Enter('Create % (%) on port %',[ToText(aHttpServerKind)^,
  597. ToText(aHttpServerSecurity)^,aPort],self);
  598. {$endif}
  599. inherited Create;
  600. SetAccessControlAllowOrigin(''); // deny CORS by default
  601. fHosts.Init(false);
  602. fDomainName := aDomainName;
  603. fPort := aPort;
  604. Split(RawUTF8(fPort),':',fPublicAddress,fPublicPort);
  605. if fPublicPort='' then begin // you should better set aPort='publicip:port'
  606. fPublicPort := fPublicAddress;
  607. fPublicAddress := ExeVersion.Host;
  608. end;
  609. fHttpServerKind := aHttpServerKind;
  610. if high(aServers)>=0 then begin
  611. for i := 0 to high(aServers) do
  612. if (aServers[i]=nil) or (aServers[i].Model=nil) then
  613. ErrMsg := 'Invalid TSQLRestServer';
  614. if ErrMsg='' then
  615. for i := 0 to high(aServers) do
  616. with aServers[i].Model do begin
  617. ServersRoot := ServersRoot+' '+Root;
  618. for j := i+1 to high(aServers) do
  619. if aServers[j].Model.URIMatch(Root)<>rmNoMatch then
  620. ErrMsg:= FormatUTF8('Duplicated Root URI: % and %',[Root,aServers[j].Model.Root]);
  621. end;
  622. if ErrMsg<>'' then
  623. raise EHttpServerException.CreateUTF8('%.Create(% ): %',[self,ServersRoot,ErrMsg]);
  624. // associate before HTTP server is started, for TSQLRestServer.BeginCurrentThread
  625. SetLength(fDBServers,length(aServers));
  626. for i := 0 to high(aServers) do
  627. SetDBServer(i,aServers[i],aHttpServerSecurity,HTTP_DEFAULT_ACCESS_RIGHTS);
  628. end;
  629. {$ifndef USETCPPREFIX}
  630. {$ifndef ONLYUSEHTTPSOCKET}
  631. if aHttpServerKind in [useHttpApi,useHttpApiRegisteringURI] then
  632. try
  633. // first try to use fastest http.sys
  634. fHttpServer := THttpApiServer.Create(false,
  635. aQueueName,HttpThreadStart,HttpThreadTerminate,GetDBServerNames);
  636. for i := 0 to high(aServers) do
  637. HttpApiAddUri(aServers[i].Model.Root,fDomainName,aHttpServerSecurity,
  638. fHttpServerKind=useHttpApiRegisteringURI,true);
  639. if aAdditionalURL<>'' then
  640. HttpApiAddUri(aAdditionalURL,fDomainName,aHttpServerSecurity,
  641. fHttpServerKind=useHttpApiRegisteringURI,true);
  642. except
  643. on E: Exception do begin
  644. fLog.Add.Log(sllError,'% for % at% -> fallback to socket-based server',
  645. [E,fHttpServer,ServersRoot],self);
  646. FreeAndNil(fHttpServer); // if http.sys initialization failed
  647. end;
  648. end;
  649. {$endif}
  650. {$endif}
  651. if fHttpServer=nil then begin
  652. // http.sys failed -> create one instance of our pure Delphi server
  653. if aHttpServerKind=useBidirSocket then
  654. fHttpServer := TWebSocketServerRest.Create(
  655. fPort,HttpThreadStart,HttpThreadTerminate,GetDBServerNames) else
  656. fHttpServer := THttpServer.Create(
  657. fPort,HttpThreadStart,HttpThreadTerminate,GetDBServerNames
  658. {$ifdef USETHREADPOOL},ServerThreadPoolCount{$endif});
  659. {$ifdef USETCPPREFIX}
  660. THttpServer(fHttpServer).TCPPrefix := 'magic';
  661. {$endif}
  662. end;
  663. fHttpServer.OnRequest := Request;
  664. if aHttpServerSecurity=secSynShaAes then
  665. fHttpServer.RegisterCompress(CompressShaAes,0); // CompressMinSize=0
  666. {$ifdef COMPRESSSYNLZ} // SynLZ registered first, since will be prefered
  667. fHttpServer.RegisterCompress(CompressSynLZ);
  668. {$endif}
  669. {$ifdef COMPRESSDEFLATE}
  670. fHttpServer.RegisterCompress(CompressGZip);
  671. {$endif}
  672. {$ifndef ONLYUSEHTTPSOCKET}
  673. if fHttpServer.InheritsFrom(THttpApiServer) then
  674. // allow fast multi-threaded requests
  675. if ServerThreadPoolCount>1 then
  676. THttpApiServer(fHttpServer).Clone(ServerThreadPoolCount-1);
  677. {$endif}
  678. // last HTTP server handling callbacks would be set for the TSQLRestServer(s)
  679. if fHttpServer.CanNotifyCallback then
  680. for i := 0 to high(fDBServers) do
  681. fDBServers[i].Server.OnNotifyCallback := NotifyCallback;
  682. fLog.Add.Log(sllHttp,'% initialized for%',[fHttpServer,ServersRoot],self);
  683. end;
  684. constructor TSQLHttpServer.Create(const aPort: AnsiString;
  685. aServer: TSQLRestServer; const aDomainName: AnsiString;
  686. aHttpServerKind: TSQLHttpServerOptions; aRestAccessRights: PSQLAccessRights;
  687. ServerThreadPoolCount: integer; aHttpServerSecurity: TSQLHttpServerSecurity;
  688. const aAdditionalURL: AnsiString; const aQueueName: SynUnicode);
  689. begin
  690. Create(aPort,[aServer],aDomainName,aHttpServerKind,ServerThreadPoolCount,
  691. aHttpServerSecurity,aAdditionalURL,aQueueName);
  692. if aRestAccessRights<>nil then
  693. DBServerAccessRight[0] := aRestAccessRights;
  694. end;
  695. destructor TSQLHttpServer.Destroy;
  696. begin
  697. fLog.Enter(self);
  698. fLog.Add.Log(sllHttp,'% finalized for % server(s)',[fHttpServer,length(fDBServers)],self);
  699. FreeAndNil(fHttpServer);
  700. inherited Destroy;
  701. end;
  702. procedure TSQLHttpServer.Shutdown;
  703. var i: integer;
  704. begin
  705. if self<>nil then
  706. for i := 0 to high(fDBServers) do
  707. fDBServers[i].Server.Shutdown;
  708. end;
  709. function TSQLHttpServer.GetDBServer(Index: Integer): TSQLRestServer;
  710. begin
  711. if (Self<>nil) and (cardinal(Index)<cardinal(length(fDBServers))) then
  712. result := fDBServers[Index].Server else
  713. result := nil;
  714. end;
  715. function TSQLHttpServer.GetDBServerCount: integer;
  716. begin
  717. result := length(fDBServers);
  718. end;
  719. function TSQLHttpServer.GetDBServerNames: RawUTF8;
  720. var i: integer;
  721. begin
  722. result := '';
  723. for i := 0 to high(fDBServers) do
  724. result := result+fDBServers[i].Server.Model.Root+' ';
  725. end;
  726. procedure TSQLHttpServer.SetDBServerAccessRight(Index: integer;
  727. Value: PSQLAccessRights);
  728. begin
  729. if Value=nil then
  730. Value := HTTP_DEFAULT_ACCESS_RIGHTS;
  731. if (Self<>nil) and (cardinal(Index)<cardinal(length(fDBServers))) then
  732. fDBServers[Index].RestAccessRights := Value;
  733. end;
  734. procedure TSQLHttpServer.SetDBServer(aIndex: integer; aServer: TSQLRestServer;
  735. aSecurity: TSQLHttpServerSecurity; aRestAccessRights: PSQLAccessRights);
  736. begin
  737. if (Self<>nil) and (cardinal(aIndex)<cardinal(length(fDBServers))) then
  738. with fDBServers[aIndex] do begin
  739. Server := aServer;
  740. if (fHttpServer<>nil) and fHttpServer.CanNotifyCallback then
  741. Server.OnNotifyCallback := NotifyCallback;
  742. Server.SetPublicURI(fPublicAddress,fPublicPort);
  743. Security := aSecurity;
  744. if aRestAccessRights=nil then
  745. RestAccessRights := HTTP_DEFAULT_ACCESS_RIGHTS else
  746. RestAccessRights := aRestAccessRights;
  747. end;
  748. end;
  749. const
  750. HTTPS_TEXT: array[boolean] of string[1] = ('','s');
  751. HTTPS_SECURITY: array[boolean] of TSQLHttpServerSecurity = (secNone, secSSL);
  752. procedure TSQLHttpServer.RootRedirectToURI(const aRedirectedURI: RawUTF8;
  753. aRegisterURI,aHttps: boolean);
  754. begin
  755. if fRootRedirectToURI[aHttps]=aRedirectedURI then
  756. exit;
  757. fLog.Add.Log(sllHttp,'Redirect http%://localhost:% to http%://localhost:%/%',
  758. [HTTPS_TEXT[aHttps],fPublicPort,HTTPS_TEXT[aHttps],fPublicPort,aRedirectedURI],self);
  759. fRootRedirectToURI[aHttps] := aRedirectedURI;
  760. if aRedirectedURI<>'' then
  761. HttpApiAddUri('/','+',HTTPS_SECURITY[aHttps],aRegisterURI,true);
  762. end;
  763. function TSQLHttpServer.HttpApiAddUri(const aRoot,aDomainName: RawByteString;
  764. aSecurity: TSQLHttpServerSecurity; aRegisterURI,aRaiseExceptionOnError: boolean): RawUTF8;
  765. {$ifndef ONLYUSEHTTPSOCKET}
  766. var err: integer;
  767. https: boolean;
  768. {$endif}
  769. begin
  770. result := ''; // no error
  771. {$ifndef ONLYUSEHTTPSOCKET}
  772. if not fHttpServer.InheritsFrom(THttpApiServer) then
  773. exit;
  774. https := aSecurity=secSSL;
  775. fLog.Add.Log(sllHttp,'http.sys registration of http%://%:%/%',
  776. [HTTPS_TEXT[https],aDomainName,fPublicPort,aRoot],self);
  777. // try to register the URL to http.sys
  778. err := THttpApiServer(fHttpServer).AddUrl(aRoot,fPublicPort,https,aDomainName,aRegisterURI);
  779. if err=NO_ERROR then
  780. exit;
  781. result := FormatUTF8('http.sys URI registration error #% for http%://%:%/%',
  782. [err,HTTPS_TEXT[https],aDomainName,fPublicPort,aRoot]);
  783. if err=ERROR_ACCESS_DENIED then
  784. if aRegisterURI then
  785. result := result+' (administrator rights needed)' else
  786. result := result+' (you need to register the URI )';
  787. fLog.Add.Log(sllLastError,result,self);
  788. if aRaiseExceptionOnError then
  789. raise EHttpServerException.CreateUTF8('%: %',[self,result]);
  790. {$endif}
  791. end;
  792. function TSQLHttpServer.Request(Ctxt: THttpServerRequest): cardinal;
  793. var call: TSQLRestURIParams;
  794. i,len: integer;
  795. P: PUTF8Char;
  796. host,redirect: RawUTF8;
  797. match: TSQLRestModelMatch;
  798. begin
  799. if ((Ctxt.URL='') or (Ctxt.URL='/')) and (Ctxt.Method='GET') then
  800. if fRootRedirectToURI[Ctxt.UseSSL]<>'' then begin
  801. Ctxt.OutCustomHeaders := 'Location: '+fRootRedirectToURI[Ctxt.UseSSL];
  802. result := HTTP_TEMPORARYREDIRECT;
  803. end else
  804. result := HTTP_BADREQUEST else
  805. if (Ctxt.Method='') or (OnlyJSONRequests and
  806. not IdemPChar(pointer(Ctxt.InContentType),JSON_CONTENT_TYPE_UPPER)) then
  807. // wrong Input parameters or not JSON request: 400 BAD REQUEST
  808. result := HTTP_BADREQUEST else
  809. if Ctxt.Method='OPTIONS' then begin
  810. // handle CORS headers control
  811. Ctxt.OutCustomHeaders := 'Access-Control-Allow-Headers: '+
  812. FindIniNameValue(pointer(Ctxt.InHeaders),'ACCESS-CONTROL-REQUEST-HEADERS: ')+
  813. fAccessControlAllowOriginHeader;
  814. result := HTTP_SUCCESS;
  815. end else begin
  816. // compute URI, handling any virtual host domain
  817. call.Init;
  818. call.LowLevelConnectionID := Ctxt.ConnectionID;
  819. if Ctxt.UseSSL then
  820. include(call.LowLevelFlags,llfSSL);
  821. if fHosts.Count>0 then begin
  822. host := FindIniNameValue(pointer(Ctxt.InHeaders),'HOST: ');
  823. i := PosEx(':',host);
  824. if i>0 then
  825. SetLength(host,i-1); // trim any port
  826. if host<>'' then
  827. host := fHosts.Value(host);
  828. end;
  829. if host<>'' then
  830. if (Ctxt.URL='') or (Ctxt.URL='/') then
  831. call.Url := host else
  832. if Ctxt.URL[1]='/' then
  833. call.Url := host+Ctxt.URL else
  834. call.Url := host+'/'+Ctxt.URL else
  835. if Ctxt.URL[1]='/' then
  836. call.Url := copy(Ctxt.URL,2,maxInt) else
  837. call.Url := Ctxt.URL;
  838. // search and call any matching TSQLRestServer instance
  839. result := HTTP_NOTFOUND; // page not found by default (in case of wrong URL)
  840. for i := 0 to high(fDBServers) do
  841. with fDBServers[i] do
  842. if Ctxt.UseSSL=(Security=secSSL) then begin // registered for http or https
  843. match := Server.Model.URIMatch(call.Url);
  844. if match=rmNoMatch then
  845. continue;
  846. if fRedirectServerRootUriForExactCase and (match=rmMatchWithCaseChange) then begin
  847. // force redirection to exact Server.Model.Root case sensitivity
  848. call.OutStatus := HTTP_TEMPORARYREDIRECT;
  849. call.OutHead := 'Location: '+Server.Model.Root+
  850. copy(call.Url,length(Server.Model.Root)+1,maxInt);
  851. end else begin
  852. // call matching TSQLRestServer.URI()
  853. call.Method := Ctxt.Method;
  854. call.InHead := Ctxt.InHeaders;
  855. call.InBody := Ctxt.InContent;
  856. call.RestAccessRights := RestAccessRights;
  857. Server.URI(call);
  858. end;
  859. // set output content
  860. result := call.OutStatus;
  861. Ctxt.OutContent := call.OutBody;
  862. Ctxt.OutContentType := call.OutBodyType;
  863. P := pointer(call.OutHead);
  864. if IdemPChar(P,'CONTENT-TYPE: ') then begin
  865. // change mime type if modified in HTTP header (e.g. GET blob fields)
  866. Ctxt.OutContentType := GetNextLine(P+14,P);
  867. call.OutHead := P;
  868. end else
  869. // default content type is JSON
  870. Ctxt.OutContentType := JSON_CONTENT_TYPE_VAR;
  871. // handle HTTP redirection over virtual hosts
  872. if (host<>'') and
  873. ((result=HTTP_MOVEDPERMANENTLY) or (result=HTTP_TEMPORARYREDIRECT)) then begin
  874. redirect := FindIniNameValue(P,'LOCATION: ');
  875. len := length(host);
  876. if (length(redirect)>len) and (redirect[len+1]='/') and
  877. IdemPropNameU(host,pointer(redirect),len) then
  878. // host/method -> method on same domain
  879. call.OutHead := 'Location: '+copy(redirect,len+1,maxInt);
  880. end;
  881. // handle optional CORS origin
  882. Ctxt.OutCustomHeaders := Trim(call.OutHead)+
  883. #13#10'Server-InternalState: '+Int32ToUtf8(call.OutInternalState);
  884. if ExistsIniName(pointer(call.InHead),'ORIGIN:') then
  885. Ctxt.OutCustomHeaders := Trim(Ctxt.OutCustomHeaders+fAccessControlAllowOriginHeader) else
  886. Ctxt.OutCustomHeaders := Trim(Ctxt.OutCustomHeaders);
  887. break;
  888. end;
  889. end;
  890. end;
  891. procedure TSQLHttpServer.HttpThreadTerminate(Sender: TThread);
  892. var i: integer;
  893. begin
  894. if self<>nil then
  895. for i := 0 to high(fDBServers) do
  896. fDBServers[i].Server.EndCurrentThread(Sender);
  897. end;
  898. procedure TSQLHttpServer.HttpThreadStart(Sender: TThread);
  899. var i: integer;
  900. begin
  901. if self=nil then
  902. exit;
  903. SetCurrentThreadName('% %/%%',[self,fPort,GetDBServerNames,Sender]);
  904. for i := 0 to high(fDBServers) do
  905. fDBServers[i].Server.BeginCurrentThread(Sender);
  906. end;
  907. procedure TSQLHttpServer.SetAccessControlAllowOrigin(const Value: RawUTF8);
  908. begin
  909. fAccessControlAllowOrigin := Value;
  910. if Value='' then
  911. fAccessControlAllowOriginHeader :=
  912. #13#10'Access-Control-Allow-Origin: ' else
  913. fAccessControlAllowOriginHeader :=
  914. #13#10'Access-Control-Allow-Methods: POST, PUT, GET, DELETE, LOCK, OPTIONS'+
  915. #13#10'Access-Control-Max-Age: 1728000'+
  916. // see http://blog.import.io/tech-blog/exposing-headers-over-cors-with-access-control-expose-headers
  917. #13#10'Access-Control-Expose-Headers: content-length,location,server-internalstate'+
  918. #13#10'Access-Control-Allow-Origin: '+Value;
  919. end;
  920. function TSQLHttpServer.WebSocketsEnable(
  921. const aWebSocketsURI, aWebSocketsEncryptionKey: RawUTF8;
  922. aWebSocketsAJAX,aWebSocketsCompressed: boolean): TWebSocketServerRest;
  923. begin
  924. if fHttpServer.InheritsFrom(TWebSocketServerRest) then begin
  925. result := TWebSocketServerRest(fHttpServer);
  926. result.WebSocketsEnable(aWebSocketsURI,aWebSocketsEncryptionKey,
  927. aWebSocketsAJAX,aWebSocketsCompressed);
  928. end else
  929. raise ESynBidirSocket.CreateUTF8(
  930. '%.WebSocketEnable(%): expected useBidirSocket',
  931. [self,GetEnumName(TypeInfo(TSQLHttpServerOptions),ord(fHttpServerKind))^]);
  932. end;
  933. function TSQLHttpServer.WebSocketsEnable(aServer: TSQLRestServer;
  934. const aWebSocketsEncryptionKey: RawUTF8;
  935. aWebSocketsAJAX,aWebSocketsCompressed: boolean): TWebSocketServerRest;
  936. begin
  937. if (aServer=nil) or (DBServerFind(aServer)<0) then
  938. raise ESynBidirSocket.CreateUTF8('%.WebSocketEnable(aServer=%?)',[self,aServer]);
  939. result := WebSocketsEnable(aServer.Model.Root,
  940. aWebSocketsEncryptionKey,aWebSocketsAJAX,aWebSocketsCompressed);
  941. end;
  942. function TSQLHttpServer.NotifyCallback(aSender: TSQLRestServer;
  943. const aInterfaceDotMethodName, aParams: RawUTF8; aConnectionID: Int64;
  944. aFakeCallID: integer; aResult, aErrorMsg: PRawUTF8): boolean;
  945. var ctxt: THttpServerRequest;
  946. status: cardinal;
  947. begin
  948. result := false;
  949. if self<>nil then
  950. try
  951. if fHttpServer<>nil then begin
  952. // aConnection.InheritsFrom(TSynThread) may raise an exception
  953. // -> checked in WebSocketsCallback/IsActiveWebSocket
  954. ctxt := THttpServerRequest.Create(nil,aConnectionID,nil);
  955. try
  956. ctxt.Prepare(FormatUTF8('%/%/%',[aSender.Model.Root,
  957. aInterfaceDotMethodName,aFakeCallID]),'POST','','['+aParams+']','');
  958. status := fHttpServer.Callback(ctxt,aResult=nil);
  959. if status=HTTP_SUCCESS then begin
  960. if aResult<>nil then
  961. aResult^ := Ctxt.OutContent;
  962. result := true;
  963. end else
  964. if aErrorMsg<>nil then
  965. aErrorMsg^ := FormatUTF8('%.Callback(%) received status=% from %',
  966. [fHttpServer,aConnectionID,status,ctxt.URL]);
  967. finally
  968. ctxt.Free;
  969. end;
  970. end else
  971. if aErrorMsg<>nil then
  972. aErrorMsg^ := FormatUTF8('%.NotifyCallback with fHttpServer=nil',[self]);
  973. except
  974. on E: Exception do
  975. if aErrorMsg<>nil then
  976. aErrorMsg^ := ObjectToJSONDebug(E);
  977. end;
  978. end;
  979. constructor TSQLHttpServer.Create(aServer: TSQLRestServer;
  980. aDefinition: TSQLHttpServerDefinition);
  981. const AUTH: array[TSQLHttpServerRestAuthentication] of TSQLRestServerAuthenticationClass = (
  982. // adDefault, adHttpBasic, adWeak, adSSPI
  983. TSQLRestServerAuthenticationDefault, TSQLRestServerAuthenticationHttpBasic,
  984. TSQLRestServerAuthenticationNone,
  985. {$ifdef MSWINDOWS}TSQLRestServerAuthenticationSSPI{$else}nil{$endif});
  986. var a: TSQLHttpServerRestAuthentication;
  987. kind: TSQLHttpServerOptions;
  988. thrdCnt: integer;
  989. websock: TWebSocketServerRest;
  990. begin
  991. if aDefinition=nil then
  992. raise EHttpServerException.CreateUTF8('%.Create(aDefinition=nil)',[self]);
  993. if aDefinition.WebSocketPassword='' then
  994. kind := HTTP_DEFAULT_MODE else
  995. kind := useBidirSocket;
  996. if aDefinition.ThreadCount=0 then
  997. thrdCnt := 32 else
  998. thrdCnt := aDefinition.ThreadCount;
  999. Create(aDefinition.BindPort,aServer,'+',kind,nil,thrdCnt,
  1000. HTTPS_SECURITY[aDefinition.Https],'',aDefinition.HttpSysQueueName);
  1001. if aDefinition.EnableCORS then
  1002. AccessControlAllowOrigin := '*';
  1003. a := aDefinition.Authentication;
  1004. if aServer.HandleAuthentication then
  1005. if AUTH[a]=nil then
  1006. fLog.Add.Log(sllWarning,'Ignored',TypeInfo(TSQLHttpServerRestAuthentication),a,self) else begin
  1007. aServer.AuthenticationUnregisterAll;
  1008. aServer.AuthenticationRegister(AUTH[a]);
  1009. end;
  1010. if aDefinition.WebSocketPassword<>'' then begin
  1011. websock := WebSocketsEnable(aServer,aDefinition.PasswordPlain);
  1012. if HttpServerFullWebSocketsLog then
  1013. websock.Settings.SetFullLog;
  1014. end;
  1015. end;
  1016. { TSQLHTTPRemoteLogServer }
  1017. constructor TSQLHTTPRemoteLogServer.Create(const aRoot: RawUTF8;
  1018. aPort: integer; const aEvent: TRemoteLogReceivedOne);
  1019. var aModel: TSQLModel;
  1020. begin
  1021. aModel := TSQLModel.Create([],aRoot);
  1022. fServer := TSQLRestServerFullMemory.Create(aModel);
  1023. aModel.Owner := fServer;
  1024. fServer.ServiceMethodRegisterPublishedMethods('',self);
  1025. fServer.AcquireExecutionMode[execSOAByMethod] := amLocked; // protect aEvent
  1026. inherited Create(AnsiString(UInt32ToUtf8(aPort)),fServer,'+',HTTP_DEFAULT_MODE,nil,1);
  1027. fEvent := aEvent;
  1028. SetAccessControlAllowOrigin('*'); // e.g. when called from AJAX/SMS
  1029. end;
  1030. destructor TSQLHTTPRemoteLogServer.Destroy;
  1031. begin
  1032. try
  1033. inherited Destroy;
  1034. finally
  1035. fServer.Free;
  1036. end;
  1037. end;
  1038. procedure TSQLHTTPRemoteLogServer.RemoteLog(Ctxt: TSQLRestServerURIContext);
  1039. begin
  1040. if Assigned(fEvent) and (Ctxt.Method=mPUT) then begin
  1041. fEvent(Ctxt.Call^.InBody);
  1042. Ctxt.Success;
  1043. end;
  1044. end;
  1045. end.