Qore HttpServer Module Reference  0.3.8
 All Classes Namespaces Functions Variables Groups Pages
HttpServer.qm.dox.h
1 // -*- mode: c++; indent-tabs-mode: nil -*-
2 // @file HttpServer.qm HTTP multi-threaded server module definition
3 
4 /* HttpServer.qm Copyright (C) 2012 - 2014 David Nichols
5 
6  Permission is hereby granted, free of charge, to any person obtaining a
7  copy of this software and associated documentation files (the "Software"),
8  to deal in the Software without restriction, including without limitation
9  the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  and/or sell copies of the Software, and to permit persons to whom the
11  Software is furnished to do so, subject to the following conditions:
12 
13  The above copyright notice and this permission notice shall be included in
14  all copies or substantial portions of the Software.
15 
16  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22  DEALINGS IN THE SOFTWARE.
23 */
24 
25 // need mime definitions
26 
27 
28 /* Version History: see docs below
29  note that this server suffers from the following limitations, among many others:
30  + not totally HTTP 1.1 compliant although claims to be
31 */
32 
218 
225 namespace HttpServer {
227 
233  hash parse_uri_query(string path);
234 
235 
237 
243  string get_exception_string(hash ex);
244 
245 };
246 
247 // class containing handler info
248 class HttpServer::HandlerInfo {
249 
250 public:
251  public :
252  string name;
253  AbstractHttpRequestHandler obj;
254  string path;
255  bool isregex;
256  // content type hash
257  hash ch;
258  *list shdr;
259 
260 public:
261 
262  constructor(string name, AbstractHttpRequestHandler obj, string path, bool isregex = True, *softlist content, *softlist shdr);
263 
264 
265  bool matchContentType(string ct);
266 
267 
269  int matchRequest(hash hdr, int score);
270 
271 };
272 
273 // class to implement handler-handling (private)
274 class HttpServer::HttpHandlerList {
275 
276 public:
277  public :
278  hash handlers;
279 
280 public:
281 
282 
283 private:
284  static checkSpecialHeaders(reference sh);
285 public:
286 
287 
289  setHandler(string name, string path, bool isregex = True, *softlist content, AbstractHttpRequestHandler obj, *softlist special_headers);
290 
291 
292  // matches a handler to the request
293  *HandlerInfo findHandler(hash hdr, reference score, bool final = False);
294 
295 
296  bool empty();
297 
298 
299  int size();
300 
301 };
302 
303 // class containing dynamic handler info
304 class HttpServer::DynamicHandlerInfo : public HttpServer::HandlerInfo {
305 
306 public:
307  public :
308  Counter counter();
309 
310 public:
311 
312  constructor(string name, AbstractHttpRequestHandler obj, string path, bool isregex = True, *softlist content, *softlist shdr);
313 
314 };
315 
316 // maintains the request count for dynamic handlers (private)
317 class HttpServer::DynamicHandlerHelper {
318 
319 public:
320 private:
321 
322 public:
323 
324  private :
325  Counter c;
326 
327 public:
328 
329  constructor(Counter c);
330 
331 
332  destructor();
333 
334 };
335 
336 // for dynamic handler-handling (private)
337 class HttpServer::DynamicHttpHandlerList : public HttpServer::HttpHandlerList {
338 
339 public:
340  private :
341  RWLock dhl();
342 
343 public:
344 
346  setHandler(string name, string path, bool isregex, *softlist content_type, AbstractHttpRequestHandler obj, *softlist special_headers);
347 
348 
350  removeHandler(string name);
351 
352 
353  *DynamicHandlerInfo findHandler(hash hdr, reference score, reference dhh);
354 
355 };
356 
358 
361 
362 public:
364 
366  bool requiresAuthentication();
367 
368 
370 
372  string getRealm();
373 
374 
376 
382  authenticate(string user, string pass = "");
383 
384 
386 
392  authenticateByIP(string ip, reference user);
393 
394 
395  private hash getAuthHeader();
396 
397 
398  private hash do401(string msg = "Authentication is required to access this server");
399 
400 
402 
411  *hash authenticateRequest(HttpListener listener, hash hdr, reference cx);
412 
413 };
414 
416 
424 
425 public:
426 private:
427 
428 public:
429 
430  private :
435 
436 public:
437 
439 
452 
453 
455 
465 
466 
468 
478  nothing recv(hash v);
479 
480 
482 
485  any send();
486 
487 
489 
499 
501 
511  abstract nothing recvImpl(hash v);
512 
514 
517  abstract any sendImpl();
518 };
519 
521 
530 
531 public:
532 private:
533 
534 public:
535 
536  private :
542  Socket s;
548  any body;
549 
550 public:
551 
554 
555 
556  hash handleRequest();
557 
558 
560 
565  private hash sendResponse();
566 
567 
569 
578  private hash getResponseHeaderMessage();
579 
580 
582 
584  private nothing recv(hash v);
585 
586 
588  private any send();
589 
590 
591  private logChunk(bool send, int size);
592 
593 
595 
607 
608 
610 
619  private nothing recvImpl(hash v);
620 
621 
623 
626  private any sendImpl();
627 
628 };
629 
631 
639 
640 public:
641  public :
644 
646  bool decompress = True;
647 
650 
652  bool stream;
653 
656 
657 public:
658 
660 
664 
665 
667  nothing persistentClosed();
668 
669 
671  private nothing checkPersistent(hash cx, hash hdr);
672 
673 
675 
698  hash handleRequest(hash cx, hash hdr, *data body);
699 
700 
702  hash handleRequest(HttpListener listener, Socket s, hash cx, hash hdr, *data body);
703 
704 
706  private AbstractStreamRequest getStreamRequestImpl(HttpListener listener, Socket s, hash cx, hash hdr, *data body);
707 
708 
710  static data decodeBody(string ce, binary body, *string enc);
711 
713  static binary encodeBody(string ce, data body);
714 
716  *data getMessageBody(Socket s, hash hdr, *data body, bool decode = True);
717 
718 
720 
727  static *string getLogMessage(hash cx, hash api, reference params, *reference args);
728 
730 
733 
734 
736 
739 
740 
742  static hash makeResponse(int code, string fmt);
743 
745  static hash makeResponse(hash hdr, int code, string fmt);
746 
748  static hash makeResponse(int code, *data body, *hash hdr);
749 
751  static hash make400(string fmt);
752 
754  static hash make400(hash hdr, string fmt);
755 
757  static hash make501(string fmt);
758 
760  static hash make501(hash hdr, string fmt);
761 
763  static hash redirect(hash cx, hash hdr, string path);
764 };
765 
768 
769 public:
770  public :
772  string url_root;
773 
774 public:
775 
777 
781 
782 
784  string getRelativePath(string path);
785 
786 };
787 
789 
792 
793 public:
794  private :
796  bool stop = False;
797 
800 
803 
805  Mutex m();
806 
807 public:
808 
810 
813 
814 
816 
830  start(softstring lid, hash cx, hash hdr, Socket s);
831 
832 
834 
838  stop(softstring lid);
839 
840 
842 
844  stop();
845 
846 
848 
874  abstract hash handleRequest(hash cx, hash hdr, *data b);
875 
877 
891  private abstract startImpl(softstring lid, hash cx, hash hdr, Socket s);
892 
894 
896  private stopImpl(string lid);
897 
898 
900  private stopImpl();
901 
902 };
903 
906 
907 public:
908  public :
910  const Version = "0.3.10";
912  const ReadTimeout = 30000; // recvs timeout after 30 seconds
914  const PollTimeout = 5000; // check for exit every 5 seconds while waiting
915 
916  // logging options
917  const LP_LOGPARAMS = 1 << 16;
918  const LP_LEVELMASK = LP_LOGPARAMS - 1;
919 
922 
924  const HttpMethods = (
925  "HEAD": True,
926  "POST": True,
927  "PUT": True,
928  "DELETE": True,
929  "GET": True,
930  "OPTIONS": True,
931  //"TRACE": True,
932  //"CONNECT": True,
933  );
934 
936  const HttpCodes = (
937  // 100s: Informational
938  "100": "Continue",
939  "101": "Switching Protocols",
940 
941  // RFC 2518: WebDAV
942  "102": "Processing",
943 
944  // 200s: Success
945  "200": "OK",
946  "201": "Created",
947  "202": "Accepted",
948  "203": "Non-Authoritative Information",
949  "204": "No Content",
950  "205": "Reset Content",
951  "206": "Partial Content",
952 
953  // RFC 4918: WebDAV: The message body that follows is an XML message and can contain a number of separate response codes, depending on how many sub-requests were made
954  "207": "Multi-Status",
955 
956  // RFC 5842: WebDAV: The members of a DAV binding have already been enumerated in a previous reply to this request, and are not being included again
957  "208": "Already Reported",
958 
959  // RFC 3229
960  "226": "IM Used",
961 
962  // 300s: Redirection
963  "300": "Multiple Choices",
964  "301": "Moved Permanently",
965  "302": "Found",
966  "303": "See Other",
967  "304": "Not Modified",
968  "305": "Use Proxy",
969  //"306": "(Reserved)",
970  "307": "Temporary Redirect",
971 
972  // 400s: Client Errors
973  "400": "Bad Request",
974  "401": "Unauthorized",
975  "402": "Payment Required",
976  "403": "Forbidden",
977  "404": "Not Found",
978  "405": "Method Not Allowed",
979  "406": "Not Acceptable",
980  "407": "Proxy Authentication Required",
981  "408": "Request Timeout",
982  "409": "Conflict",
983  "410": "Gone",
984  "411": "Length Required",
985  "412": "Precondition Failed",
986  "413": "Request Entity Too Large",
987  "414": "Request-URI Too Long",
988  "415": "Unsupported Media Type",
989  "416": "Requested Range Not Satisfiable",
990  "417": "Expectation Failed",
991 
992  // RFC 2324: http://tools.ietf.org/html/rfc2324
993  "418": "I'm a teapot",
994 
995  // Returned by the Twitter Search and Trends API when the client is being rate limited
996  "420": "Enhance Yextern Calm",
997 
998  // RFC 4918: WebDAV: The request was well-formed but was unable to be followed due to semantic errors
999  "422": "Unprocessable Entity",
1000 
1001  // RFC 4918: WebDAV: The resource that is being accessed is locked
1002  "423": "Locked",
1003 
1004  // RFC 4918: WebDAV: The request failed due to failure of a previous request (e.g. a PROPPATCH)
1005  "424": "Failed Dependency",
1006 
1007  // Internet draft: Defined in drafts of "WebDAV Advanced Collections Protocol", but not present in "Web Distributed Authoring and Versioning (WebDAV) Ordered Collections Protocol"
1008  "425": "Unordered Collection",
1009 
1010  // RFC 2817: The client should switch to a different protocol such as TLS/1.0
1011  "426": "Upgrade Required",
1012 
1013  // RFC 6585: The origin server requires the request to be conditional. Intended to prevent "the 'lost update' problem, where a client GETs a resource's state, modifies it, and PUTs it back to the server, when meanwhile a third party has modified the state on the server, leading to a conflict."
1014  "428": "Precondition Required",
1015 
1016  // RFC 6585: The user has sent too many requests in a given amount of time. Intended for use with rate limiting schemes
1017  "429": "Too Many Requests",
1018 
1019  // RFC 6585
1020  "431": "Request Header Fields Too Large",
1021 
1022  // 500s: Server Errors
1023  "500": "Internal Server Error",
1024  "501": "Not Implemented",
1025  "502": "Bad Gateway",
1026  "503": "Service Unavailable",
1027  "504": "Gateway Timeout",
1028  "505": "HTTP Version Not Supported",
1029  "509": "Bandwidth Limit Exceeded",
1030 
1031  // RFC 2774: Further extensions to the request are required for the server to fulfill it
1032  "510": "Not Extended",
1033 
1034  // RFC 6585: The client needs to authenticate to gain network access. Intended for use by intercepting proxies used to control access to the network (e.g. "captive portals" used to require agreement to Terms of Service before granting full Internet access via a Wi-Fi hotspot)
1035  "511": "Network Authentication Required",
1036  );
1037 
1040  "gzip": "gzip",
1041  "deflate": "deflate",
1042  "bzip2": "bzip2",
1043  "x-gzip": "gzip",
1044  "x-deflate": "deflate",
1045  "x-bzip2": "bzip2",
1046  );
1047 
1050 
1052  const CompressionThreshold = 1024;
1053 
1054 public:
1055 
1057  private :
1058  *code logfunc;
1059  *code errlogfunc;
1060 
1061  // quit server flag
1062  bool exit = False;
1063 
1064  // if True then verbose exception info will be logged
1065  bool debug;
1066 
1067  Sequence seqSessions();
1068  Sequence seqListeners();
1069 
1070  bool stopped = False;
1071 
1072  // permanent handlers; these handlers are never removed
1073  HttpHandlerList handlers();
1074 
1075  // default handler
1076  hash defaultHandler;
1077 
1078  // hash of listeners keyed by listener ID
1079  hash listeners;
1080 
1081  // map of bind addresses to listener IDs
1082  hash smap;
1083 
1084  // map of listener names to listener IDs
1085  hash nmap;
1086 
1087  // listener Gate
1088  Gate lm();
1089 
1090  // running listener counter
1091  Counter c();
1092 
1093  // dynamic handlers
1094  DynamicHttpHandlerList dhandlers();
1095 
1096  // connection thread pool
1097  ThreadPool threadPool(-1, DefaultIdleThreads);
1098 
1099  // other misc response headers
1100  hash hdr;
1101 
1102  // override message body encoding if none is received from the sender; http://tools.ietf.org/html/rfc2616#section-3.7.1 states that it must be iso-8850-1
1103  *string override_encoding;
1104 
1105  static string HttpServerString;
1106 
1107 public:
1109 
1111 
1119  constructor(*code logfunc, *code errlogfunc, bool dbg = False, string name = sprintf("Qore-HTTP-Server/%s", HttpServer::Version), hash hdr = ("X-Powered-By": "Qore/" + Qore::VersionString));
1120 
1121 
1123  destructor();
1124 
1125 
1127  static string getHttpServerVersionString();
1128 
1129  setDefaultTextEncoding(string enc);
1130 
1131 
1132  string getDefaultTextEncoding();
1133 
1134 
1136 
1164  final list addListenersWithHandler(string hname, AbstractHttpRequestHandler handler, hash lp, *code logger, *code errorlogger, *code stopc, *string name, int family = AF_UNSPEC);
1165 
1166 
1168 
1183  hash addListener(softstring sock, *string cert_path, *string key_path, *string name, int family = AF_UNSPEC);
1184 
1185 
1187 
1202  softlist addListeners(softstring sock, *string cert_path, *string key_path, *string name, int family = AF_UNSPEC);
1203 
1204 
1206 
1220  list addINETListeners(*string node, softstring service, *string cert_path, *string key_path, *string name, int family = AF_UNSPEC);
1221 
1222 
1224  copy();
1225 
1226 
1228 
1230  hash getListeners();
1231 
1232 
1234 
1251  hash getListenerInfo(softint id);
1252 
1253 
1255 
1272  hash getListenerInfoName(string name);
1273 
1274 
1276  int getListenerCount();
1277 
1278 
1280 
1282  stopNoWait();
1283 
1284 
1286  waitStop();
1287 
1288 
1289  // only called from the listeners - do not call externally
1290  listenerStopped(HttpListener l);
1291 
1292 
1294 
1296  stop();
1297 
1298 
1300  stopListener(softstring bind);
1301 
1302 
1304  stopListenerID(softint id);
1305 
1306 
1308  int getListenerTID(softint id);
1309 
1310 
1313 
1314 
1316  setHandler(string name, string path, *softlist content_type, AbstractHttpRequestHandler obj, *softlist special_headers, bool isregex = True);
1317 
1318 
1320  setDynamicHandler(string name, string path, *softlist content_type, AbstractHttpRequestHandler obj, *softlist special_headers, bool isregex = True);
1321 
1322 
1324  setHandler(string name, AbstractUrlHandler obj);
1325 
1326 
1328  setDynamicHandler(string name, AbstractUrlHandler obj);
1329 
1330 
1332  addHandlerToListener(softstring bind, string name, string path, *softlist content_type, AbstractHttpRequestHandler obj, *softlist special_headers, bool isregex = True);
1333 
1334 
1336  addHandlerToListenerID(softint id, string name, string path, *softlist content_type, AbstractHttpRequestHandler obj, *softlist special_headers, bool isregex = True);
1337 
1338 
1340  addHandlerToListener(softstring bind, string name, AbstractUrlHandler obj);
1341 
1342 
1344  addHandlerToListenerID(softint id, string name, AbstractUrlHandler obj);
1345 
1346 
1348  removeDynamicHandler(string name);
1349 
1350 
1352  log();
1353 
1354 
1356  logError();
1357 
1358 
1360  logArgs(softlist args = ());
1361 
1362 
1364  logErrorArgs(softlist args = ());
1365 
1366 
1368  sendHttpError(HttpListener listener, hash cx, Socket s, int code, string msg, *hash extra_hdrs, *string encoding);
1369 
1370 
1372 
1374  static string getURLFromBind(softstring bind, *string host);
1375 
1377  setDebug(bool dbg = True);
1378 
1379 
1381  bool getDebug();
1382 
1383 
1384  startConnection(code c);
1385 
1386 
1388  static nothing setReplyHeaders(Socket s, hash cx, reference rv);
1389 
1391  // don't reimplement this method; fix/enhance it in the module
1392  final private HttpListener addListenerIntern(*string node, *softstring service, *Qore::SSLCertificate cert, *Qore::SSLPrivateKey key, *hash hi, *code logger, *code errorlogger, *code stopc, *string name, int family = AF_UNSPEC);
1393 
1394 
1395  // don't reimplement this method; fix/enhance it in the module
1396  static final private hash getSSLObjects(string cert_path, *string key_path);
1397 
1398  // don't reimplement this method; fix/enhance it in the module
1399  final private list addINETListenersIntern(*string node, softstring service, *hash sd, *hash lp, *code logger, *code errorlogger, *code stopc, *string name, int family = AF_UNSPEC);
1400 
1401 
1402  // don't reimplement this method; fix/enhance it in the module
1403  final private hash noHandlerError(hash cx, hash hdr, any body);
1404 
1405 
1406  // handles an incoming request - do not call externally; this method is called by the listeners when a request is received
1407  // don't reimplement this method; fix/enhance it in the module
1408  final handleRequest(HttpListener listener, Socket s, reference cx, hash hdr, hash hh, *data body, bool head = False, HttpPersistentHandlerInfo phi);
1409 
1410 
1411  // sends a reply to a request
1412  // don't reimplement this method; fix/enhance it in the module
1413  final sendReply(HttpListener listener, Socket s, AbstractHttpRequestHandler handler, hash rv, reference cx, hash hdr, bool head);
1414 
1416 };
1417 
1418 class HttpServer::HttpPersistentHandlerInfo {
1419 
1420 public:
1421  public :
1422  *DynamicHandlerHelper dhh;
1423  *AbstractHttpRequestHandler handler;
1424 
1425 public:
1426 
1427  destructor();
1428 
1429 
1430  assign(DynamicHandlerHelper dhh, AbstractHttpRequestHandler handler);
1431 
1432 
1433  clear();
1434 
1435 };
1436 
1439 
1440 public:
1441  private :
1442  HttpServer serv;
1443  Sequence ss;
1444  *SSLCertificate cert;
1445  *SSLPrivateKey key;
1446  bool ssl = False;
1447  any socket;
1448  hash socket_info;
1449 
1450  // connection counter
1451  Counter cThreads();
1452  bool exit = False;
1453  bool stopped = False;
1454  int id;
1455 
1456  // socket handler hash
1457  hash shh;
1458 
1459  // mutex
1460  Mutex m();
1461 
1462  // code references to external logging functions
1463  *code logger;
1464  *code errorlogger;
1465 
1466  // stop notification closure
1467  *code stopc;
1468 
1469  string name;
1470 
1471  const PollInterval = 1s;
1472  const ListenQueue = 100;
1473 
1474 public:
1475 
1476  public :
1477  // TID of the background listener thread
1478  int tid;
1479 
1480  // listener-specific handlers
1481  HttpHandlerList handlers();
1482 
1483  // default handler info
1484  *HandlerInfo defaultHandler;
1485 
1486 public:
1487 
1488  // params: server, id, session ID sequence object, socket, rbac obj, [cert, key]
1489  constructor(HttpServer server, int id, Sequence ss, *string node, *softstring service, *Qore::SSLCertificate cert, *Qore::SSLPrivateKey key, *hash hi, *code logger, *code errorlogger, *code stopc, string name, int family = AF_UNSPEC);
1490 
1491 
1492  addHandlers(hash hi);
1493 
1494 
1495  setDefaultHandler(string name);
1496 
1497 
1498  copy();
1499 
1500 
1501  destructor();
1502 
1503 
1504  string getName();
1505 
1506 
1507  any getAddress();
1508 
1509 
1510  int getID();
1511 
1512 
1513  bool isSecure();
1514 
1515 
1516  hash getInfo();
1517 
1518 
1519  any removeUserThreadContext(string k);
1520 
1521 
1522  addUserThreadContext(hash uctx);
1523 
1524 
1525  stopNoWait();
1526 
1527 
1528  stop();
1529 
1530 
1531  logResponse(hash cx, int code, *data body, *hash hdr);
1532 
1533 
1534  logResponse(hash cx, hash rv);
1535 
1536 
1537  log();
1538 
1539 
1540  logError();
1541 
1542 
1543  private mainThread();
1544 
1545 
1546  // thread for handling communication per connection
1547  private connectionThread(Socket s);
1548 
1549 
1550  bool registerDedicatedSocket(softstring id, AbstractHttpSocketHandler h);
1551 
1552 
1553  removeDedicatedSocket(softstring id, AbstractHttpSocketHandler h);
1554 
1555 };
constructor(HttpListener listener, AbstractHttpRequestHandler handler, Socket s, hash cx, hash hdr, any body)
creates the object with the given attributes
logError()
called to log error information to the registered error log code
logErrorArgs(softlist args=())
calls the error log function/closure with the given args
logArgs(softlist args=())
calls the log function/closure with the given args
any send()
this method provides the callback method for sending chunked data by calling sendImpl() ...
abstract nothing recvImpl(hash v)
abstract callback method for receiving chunked data
const AF_UNSPEC
string sprintf(string fmt,...)
hash getListeners()
returns a hash of listener information
hash hdr
a hash of request headers
Definition: HttpServer.qm.dox.h:546
hash addListener(softstring sock, *string cert_path, *string key_path, *string name, int family=AF_UNSPEC)
adds a global listener to the server
private nothing recvImpl(hash v)
abstract callback method for receiving chunked data
string get_exception_string(hash ex)
returns a multi-line string from the exception hash argument suitable for logging or output on the co...
abstract class for streaming HTTP chunked requests/responses
Definition: HttpServer.qm.dox.h:529
abstract hash handleRequest(hash cx, hash hdr, *data b)
called by the HTTP server to handle incoming HTTP requests
setDebug(bool dbg=True)
turns on or off debugging; when debugging is enabled more verbose error messages are reported ...
string getRealm()
returns the authentication realm as a string
abstract class that all HTTP request handler objects must inherit from
Definition: HttpServer.qm.dox.h:638
*AbstractAuthenticator auth
the optional AbstractAuthenticator for requests to this handler
Definition: HttpServer.qm.dox.h:643
static string getURLFromBind(softstring bind, *string host)
returns a complete URL from a bind address
constructor(hash cx)
creates the object with the given arguments
const ReadTimeout
default read timeout in ms
Definition: HttpServer.qm.dox.h:912
removeDynamicHandler(string name)
remove dynamic handler
hash lh
hash of listener references; this is to stop all connections associated with a particular listener ...
Definition: HttpServer.qm.dox.h:799
*hash ex
if an exception is raised in a callback then the exception hash is saved here
Definition: HttpServer.qm.dox.h:434
addHandlerToListenerID(softint id, string name, string path, *softlist content_type, AbstractHttpRequestHandler obj, *softlist special_headers, bool isregex=True)
adds a request handler to a listener given the listener's id
destructor()
calls stop() and destroys the object
addHandlerToListener(softstring bind, string name, string path, *softlist content_type, AbstractHttpRequestHandler obj, *softlist special_headers, bool isregex=True)
adds a request handler to a listener given the listener's name or bind address
const True
start(softstring lid, hash cx, hash hdr, Socket s)
called from the HTTP server after the handleRequest() method indicates that a dedicated connection sh...
string getRelativePath(string path)
returns the relative path anchored from the url_root if possible; URI query arguments are stripped of...
bool persistent
persistent connection flag
Definition: HttpServer.qm.dox.h:655
setDynamicHandler(string name, string path, *softlist content_type, AbstractHttpRequestHandler obj, *softlist special_headers, bool isregex=True)
sets a dynamic request handler according to the arguments given
*data getMessageBody(Socket s, hash hdr, *data body, bool decode=True)
optionally retrieves and post-processes any message body
const DefaultIdleThreads
default number of idle threads to have waiting for new connections (accross all listeners) ...
Definition: HttpServer.qm.dox.h:1049
stopListener(softstring bind)
stops a single listener based on its name or bind address; does not return until all connections on t...
stopListenerID(softint id)
stops a single listener based on its listener ID; does not return until all connections on the listen...
private hash sendResponse()
called to either create the response hash or send a chunked response directly
const HttpMethods
supported HTTP methods
Definition: HttpServer.qm.dox.h:924
AbstractHttpRequestHandler handler
the request handler for the request
Definition: HttpServer.qm.dox.h:540
nothing recv(hash v)
this method provides the callback method for receiving chunked data by calling recvImpl() ...
bool decompress
if POSTed data should be decompressed automatically if there is content-encoding
Definition: HttpServer.qm.dox.h:646
abstract private startImpl(softstring lid, hash cx, hash hdr, Socket s)
called from the HTTP server after the handleRequest() method indicates that a dedicated connection sh...
hash cx
call context hash
Definition: HttpServer.qm.dox.h:432
private hash getResponseHeaderMessageImpl()
this method should return the response message description hash
stop()
stops all listeners; only returns when all connections are closed on all listeners ...
binary binary()
bool stream
if the handler supports streaming requests/responses with chunked data
Definition: HttpServer.qm.dox.h:652
constructor(*AbstractAuthenticator auth, softbool stream=False)
create the object optionally with the given AbstractAuthenticator
constructor(string url_root, *AbstractAuthenticator auth)
creates the object based on the URL root and optional authenticator
Mutex m()
listener reference hash mutex
abstract class for embedded objects serving streaming requests
Definition: HttpServer.qm.dox.h:423
private stopImpl()
called from the HTTP server when the socket should be closed due to an external request; the start() ...
static hash make501(string fmt)
creates a hash for an HTTP 501 error response with the response message body as a string ...
constructor(*code logfunc, *code errlogfunc, bool dbg=False, string name=sprintf("Qore-HTTP-Server/%s", HttpServer::Version), hash hdr=("X-Powered-By":"Qore/"+Qore::VersionString))
creates the HttpServer
const False
bool requiresAuthentication()
called to check if the connection requires authentication
list list(...)
abstract base class for external authentication
Definition: HttpServer.qm.dox.h:360
static hash makeResponse(int code, string fmt)
creates a hash for an HTTP response with the response code and the response message body as a formatt...
static hash make400(string fmt)
creates a hash for an HTTP 400 error response with the response message body as a string ...
hash getListenerInfo(softint id)
returns a hash of information about the listener given the listener ID
restoreThreadLocalData(*hash data)
called after handleRequest() with any data returned from saveThreadData()
private nothing recv(hash v)
this is the primary callback for receiving chunked data; data will be logged, and then recvImpl() is ...
stop()
called from the HTTP server when the socket should be closed due to an external request; the start() ...
const PollTimeout
default poll timeout in ms
Definition: HttpServer.qm.dox.h:914
hash cx
the call context variable
Definition: HttpServer.qm.dox.h:544
Socket s
the Socket object for the response
Definition: HttpServer.qm.dox.h:542
softlist addListeners(softstring sock, *string cert_path, *string key_path, *string name, int family=AF_UNSPEC)
adds one or more global listeners according to the bind address
private any sendImpl()
abstract callback method for sending chunked data
constructor(*AbstractAuthenticator auth)
create the object optionally with the given AbstractAuthenticator
nothing exit(softint rc=0)
hash parse_uri_query(string path)
parses a URI path for a arguments and a method; where the method is the part of the path before the f...
static binary encodeBody(string ce, data body)
encodes a message body with content-encoding
final list addListenersWithHandler(string hname, AbstractHttpRequestHandler handler, hash lp, *code logger, *code errorlogger, *code stopc, *string name, int family=AF_UNSPEC)
adds a dedicated listener to the server with an explicit/dedicated handler for incoming connections ...
static string getHttpServerVersionString()
returns the HTTP server version string
static *string getLogMessage(hash cx, hash api, reference params, *reference args)
helper method for handling log messages
sendHttpError(HttpListener listener, hash cx, Socket s, int code, string msg, *hash extra_hdrs, *string encoding)
sends an HTTP error message on the socket
stopNoWait()
stops all listeners; does not wait for all connections on the listeners to close
bool getDebug()
returns the current status of the debug flag
private AbstractStreamRequest getStreamRequestImpl(HttpListener listener, Socket s, hash cx, hash hdr, *data body)
returns the AbstractStreamRequest object for handling chunked requests
abstract any sendImpl()
abstract callback method for sending chunked data
const CompressionThreshold
default threadhold for data compressions; transfers smaller than this size will not be compressed ...
Definition: HttpServer.qm.dox.h:1052
abstract hash getResponseHeaderMessageImpl()
this method should return the response message description hash
private any send()
this is the primary callback for sending chunked responses; first sendImpl() is called to get the raw...
abstract class that all HTTP dedicated socket handler objects must inherit from
Definition: HttpServer.qm.dox.h:791
abstract class for HTTP request handlers anchored at a specific URL
Definition: HttpServer.qm.dox.h:767
waitStop()
waits for all listeners to be stopped; call after calling HttpServer::stopNoWait() ...
static data decodeBody(string ce, binary body, *string enc)
decodes a message body with content-encoding
hash handleRequest(hash cx, hash hdr, *data body)
will be called when a request is received that should be directed to the handler
static nothing setReplyHeaders(Socket s, hash cx, reference rv)
helper method to set HTTP response headers
const AIFlags
address info flags
Definition: HttpServer.qm.dox.h:921
private hash getResponseHeaderMessage()
this method returns the response message description hash by calling getResponseHeaderMessageImpl() ...
bool decompress_to_string
if automatically decompressed POSTed data should be converted to a string (if False, then it will be decompressed to a binary)
Definition: HttpServer.qm.dox.h:649
copy()
throws an exception; these objects do not support copying
const Version
version of the HttpServer's implementation
Definition: HttpServer.qm.dox.h:910
setDefaultHandler(string name, AbstractHttpRequestHandler obj)
sets the default request handler when no other handler can be matched
The HttpServer class implements a multithreaded HTTP server primarily designed for serving RPC-style ...
Definition: HttpServer.qm.dox.h:905
authenticate(string user, string pass="")
called to authenticate a user for a connection
HttpListener listener
the listener servicing the request for logging purposes
Definition: HttpServer.qm.dox.h:538
hash getResponseHeaderMessage()
this method returns the response message description hash by calling getResponseHeaderMessageImpl() ...
setHandler(string name, string path, *softlist content_type, AbstractHttpRequestHandler obj, *softlist special_headers, bool isregex=True)
sets a request handler according to the arguments given
int getListenerCount()
returns the number of running HTTP listeners
this class implements the listeners for the HttpServer class
Definition: HttpServer.qm.dox.h:1438
log()
called to log information to the registered log code
const VersionString
*hash saveThreadLocalData()
called before handleRequest() any data returned here will be given to restoreThreadLocalData() after ...
list addINETListeners(*string node, softstring service, *string cert_path, *string key_path, *string name, int family=AF_UNSPEC)
adds one or more global listeners according to the bind address
authenticateByIP(string ip, reference user)
called when the connection requires authentication, but no authentication credentials were supplied...
hash hash(object obj)
string url_root
root part of URL for matching requests
Definition: HttpServer.qm.dox.h:772
const AI_ADDRCONFIG
hash getListenerInfoName(string name)
returns a hash of information about the listener given the listener name or bind ID ...
const HttpCodes
map of HTTP result codes and text messages
Definition: HttpServer.qm.dox.h:936
nothing persistentClosed()
called externally when a persistent connection is closed
const AI_PASSIVE
static hash redirect(hash cx, hash hdr, string path)
generates a redirect hash for the given path
*hash authenticateRequest(HttpListener listener, hash hdr, reference cx)
primary method called to authenticate each request
hash lsh
hash of listener stop flags
Definition: HttpServer.qm.dox.h:802
any body
any message body given in a non-chunked request; could already be deserialized
Definition: HttpServer.qm.dox.h:548
private nothing checkPersistent(hash cx, hash hdr)
this method will throw an exception if a persistent connection cannot be granted
const ContentEncodings
content-encodings supported; this is a hash to simulate a set with O(ln(n)) access times ...
Definition: HttpServer.qm.dox.h:1039
int getListenerTID(softint id)
gets the TID of a listener based on its listener ID