HTTP and HTTPS library for Mbed OS 5

Dependents:   MQTTGateway2 MQTTGatewayK64 http-example-wnc GuardRoom ... more

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers http_parser.h Source File

http_parser.h

00001 /* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
00002  *
00003  * Permission is hereby granted, free of charge, to any person obtaining a copy
00004  * of this software and associated documentation files (the "Software"), to
00005  * deal in the Software without restriction, including without limitation the
00006  * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
00007  * sell copies of the Software, and to permit persons to whom the Software is
00008  * furnished to do so, subject to the following conditions:
00009  *
00010  * The above copyright notice and this permission notice shall be included in
00011  * all copies or substantial portions of the Software.
00012  *
00013  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
00014  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
00015  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
00016  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
00017  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
00018  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
00019  * IN THE SOFTWARE.
00020  */
00021 #ifndef http_parser_h
00022 #define http_parser_h
00023 
00024 #ifdef __cplusplus
00025 extern "C" {
00026 #endif
00027 
00028 /* Also update SONAME in the Makefile whenever you change these. */
00029 #define HTTP_PARSER_VERSION_MAJOR 2
00030 #define HTTP_PARSER_VERSION_MINOR 7
00031 #define HTTP_PARSER_VERSION_PATCH 1
00032 
00033 #if defined(_WIN32) && !defined(__MINGW32__) && \
00034   (!defined(_MSC_VER) || _MSC_VER<1600) && !defined(__WINE__)
00035 #include <BaseTsd.h>
00036 #include <stddef.h>
00037 typedef __int8 int8_t;
00038 typedef unsigned __int8 uint8_t;
00039 typedef __int16 int16_t;
00040 typedef unsigned __int16 uint16_t;
00041 typedef __int32 int32_t;
00042 typedef unsigned __int32 uint32_t;
00043 typedef __int64 int64_t;
00044 typedef unsigned __int64 uint64_t;
00045 #else
00046 #include <stdint.h>
00047 #endif
00048 
00049 /* Compile with -DHTTP_PARSER_STRICT=0 to make less checks, but run
00050  * faster
00051  */
00052 #ifndef HTTP_PARSER_STRICT
00053 # define HTTP_PARSER_STRICT 1
00054 #endif
00055 
00056 /* Maximium header size allowed. If the macro is not defined
00057  * before including this header then the default is used. To
00058  * change the maximum header size, define the macro in the build
00059  * environment (e.g. -DHTTP_MAX_HEADER_SIZE=<value>). To remove
00060  * the effective limit on the size of the header, define the macro
00061  * to a very large number (e.g. -DHTTP_MAX_HEADER_SIZE=0x7fffffff)
00062  */
00063 #ifndef HTTP_MAX_HEADER_SIZE
00064 # define HTTP_MAX_HEADER_SIZE (80*1024)
00065 #endif
00066 
00067 typedef struct http_parser http_parser;
00068 typedef struct http_parser_settings http_parser_settings;
00069 
00070 
00071 /* Callbacks should return non-zero to indicate an error. The parser will
00072  * then halt execution.
00073  *
00074  * The one exception is on_headers_complete. In a HTTP_RESPONSE parser
00075  * returning '1' from on_headers_complete will tell the parser that it
00076  * should not expect a body. This is used when receiving a response to a
00077  * HEAD request which may contain 'Content-Length' or 'Transfer-Encoding:
00078  * chunked' headers that indicate the presence of a body.
00079  *
00080  * Returning `2` from on_headers_complete will tell parser that it should not
00081  * expect neither a body nor any futher responses on this connection. This is
00082  * useful for handling responses to a CONNECT request which may not contain
00083  * `Upgrade` or `Connection: upgrade` headers.
00084  *
00085  * http_data_cb does not return data chunks. It will be called arbitrarily
00086  * many times for each string. E.G. you might get 10 callbacks for "on_url"
00087  * each providing just a few characters more data.
00088  */
00089 typedef int (*http_data_cb) (http_parser*, const char *at, uint32_t length);
00090 typedef int (*http_cb) (http_parser*);
00091 
00092 
00093 /* Status Codes */
00094 #define HTTP_STATUS_MAP(XX)                                                 \
00095   XX(100, CONTINUE,                        Continue)                        \
00096   XX(101, SWITCHING_PROTOCOLS,             Switching Protocols)             \
00097   XX(102, PROCESSING,                      Processing)                      \
00098   XX(200, OK,                              OK)                              \
00099   XX(201, CREATED,                         Created)                         \
00100   XX(202, ACCEPTED,                        Accepted)                        \
00101   XX(203, NON_AUTHORITATIVE_INFORMATION,   Non-Authoritative Information)   \
00102   XX(204, NO_CONTENT,                      No Content)                      \
00103   XX(205, RESET_CONTENT,                   Reset Content)                   \
00104   XX(206, PARTIAL_CONTENT,                 Partial Content)                 \
00105   XX(207, MULTI_STATUS,                    Multi-Status)                    \
00106   XX(208, ALREADY_REPORTED,                Already Reported)                \
00107   XX(226, IM_USED,                         IM Used)                         \
00108   XX(300, MULTIPLE_CHOICES,                Multiple Choices)                \
00109   XX(301, MOVED_PERMANENTLY,               Moved Permanently)               \
00110   XX(302, FOUND,                           Found)                           \
00111   XX(303, SEE_OTHER,                       See Other)                       \
00112   XX(304, NOT_MODIFIED,                    Not Modified)                    \
00113   XX(305, USE_PROXY,                       Use Proxy)                       \
00114   XX(307, TEMPORARY_REDIRECT,              Temporary Redirect)              \
00115   XX(308, PERMANENT_REDIRECT,              Permanent Redirect)              \
00116   XX(400, BAD_REQUEST,                     Bad Request)                     \
00117   XX(401, UNAUTHORIZED,                    Unauthorized)                    \
00118   XX(402, PAYMENT_REQUIRED,                Payment Required)                \
00119   XX(403, FORBIDDEN,                       Forbidden)                       \
00120   XX(404, NOT_FOUND,                       Not Found)                       \
00121   XX(405, METHOD_NOT_ALLOWED,              Method Not Allowed)              \
00122   XX(406, NOT_ACCEPTABLE,                  Not Acceptable)                  \
00123   XX(407, PROXY_AUTHENTICATION_REQUIRED,   Proxy Authentication Required)   \
00124   XX(408, REQUEST_TIMEOUT,                 Request Timeout)                 \
00125   XX(409, CONFLICT,                        Conflict)                        \
00126   XX(410, GONE,                            Gone)                            \
00127   XX(411, LENGTH_REQUIRED,                 Length Required)                 \
00128   XX(412, PRECONDITION_FAILED,             Precondition Failed)             \
00129   XX(413, PAYLOAD_TOO_LARGE,               Payload Too Large)               \
00130   XX(414, URI_TOO_LONG,                    URI Too Long)                    \
00131   XX(415, UNSUPPORTED_MEDIA_TYPE,          Unsupported Media Type)          \
00132   XX(416, RANGE_NOT_SATISFIABLE,           Range Not Satisfiable)           \
00133   XX(417, EXPECTATION_FAILED,              Expectation Failed)              \
00134   XX(421, MISDIRECTED_REQUEST,             Misdirected Request)             \
00135   XX(422, UNPROCESSABLE_ENTITY,            Unprocessable Entity)            \
00136   XX(423, LOCKED,                          Locked)                          \
00137   XX(424, FAILED_DEPENDENCY,               Failed Dependency)               \
00138   XX(426, UPGRADE_REQUIRED,                Upgrade Required)                \
00139   XX(428, PRECONDITION_REQUIRED,           Precondition Required)           \
00140   XX(429, TOO_MANY_REQUESTS,               Too Many Requests)               \
00141   XX(431, REQUEST_HEADER_FIELDS_TOO_LARGE, Request Header Fields Too Large) \
00142   XX(451, UNAVAILABLE_FOR_LEGAL_REASONS,   Unavailable For Legal Reasons)   \
00143   XX(500, INTERNAL_SERVER_ERROR,           Internal Server Error)           \
00144   XX(501, NOT_IMPLEMENTED,                 Not Implemented)                 \
00145   XX(502, BAD_GATEWAY,                     Bad Gateway)                     \
00146   XX(503, SERVICE_UNAVAILABLE,             Service Unavailable)             \
00147   XX(504, GATEWAY_TIMEOUT,                 Gateway Timeout)                 \
00148   XX(505, HTTP_VERSION_NOT_SUPPORTED,      HTTP Version Not Supported)      \
00149   XX(506, VARIANT_ALSO_NEGOTIATES,         Variant Also Negotiates)         \
00150   XX(507, INSUFFICIENT_STORAGE,            Insufficient Storage)            \
00151   XX(508, LOOP_DETECTED,                   Loop Detected)                   \
00152   XX(510, NOT_EXTENDED,                    Not Extended)                    \
00153   XX(511, NETWORK_AUTHENTICATION_REQUIRED, Network Authentication Required) \
00154 
00155 enum http_status
00156   {
00157 #define XX(num, name, string) HTTP_STATUS_##name = num,
00158   HTTP_STATUS_MAP(XX)
00159 #undef XX
00160   };
00161 
00162 
00163 /* Request Methods */
00164 #define HTTP_METHOD_MAP(XX)         \
00165   XX(0,  DELETE,      DELETE)       \
00166   XX(1,  GET,         GET)          \
00167   XX(2,  HEAD,        HEAD)         \
00168   XX(3,  POST,        POST)         \
00169   XX(4,  PUT,         PUT)          \
00170   /* pathological */                \
00171   XX(5,  CONNECT,     CONNECT)      \
00172   XX(6,  OPTIONS,     OPTIONS)      \
00173   XX(7,  TRACE,       TRACE)        \
00174   /* WebDAV */                      \
00175   XX(8,  COPY,        COPY)         \
00176   XX(9,  LOCK,        LOCK)         \
00177   XX(10, MKCOL,       MKCOL)        \
00178   XX(11, MOVE,        MOVE)         \
00179   XX(12, PROPFIND,    PROPFIND)     \
00180   XX(13, PROPPATCH,   PROPPATCH)    \
00181   XX(14, SEARCH,      SEARCH)       \
00182   XX(15, UNLOCK,      UNLOCK)       \
00183   XX(16, BIND,        BIND)         \
00184   XX(17, REBIND,      REBIND)       \
00185   XX(18, UNBIND,      UNBIND)       \
00186   XX(19, ACL,         ACL)          \
00187   /* subversion */                  \
00188   XX(20, REPORT,      REPORT)       \
00189   XX(21, MKACTIVITY,  MKACTIVITY)   \
00190   XX(22, CHECKOUT,    CHECKOUT)     \
00191   XX(23, MERGE,       MERGE)        \
00192   /* upnp */                        \
00193   XX(24, MSEARCH,     M-SEARCH)     \
00194   XX(25, NOTIFY,      NOTIFY)       \
00195   XX(26, SUBSCRIBE,   SUBSCRIBE)    \
00196   XX(27, UNSUBSCRIBE, UNSUBSCRIBE)  \
00197   /* RFC-5789 */                    \
00198   XX(28, PATCH,       PATCH)        \
00199   XX(29, PURGE,       PURGE)        \
00200   /* CalDAV */                      \
00201   XX(30, MKCALENDAR,  MKCALENDAR)   \
00202   /* RFC-2068, section 19.6.1.2 */  \
00203   XX(31, LINK,        LINK)         \
00204   XX(32, UNLINK,      UNLINK)       \
00205 
00206 enum http_method
00207   {
00208 #define XX(num, name, string) HTTP_##name = num,
00209   HTTP_METHOD_MAP(XX)
00210 #undef XX
00211   };
00212 
00213 
00214 enum http_parser_type { HTTP_REQUEST, HTTP_RESPONSE, HTTP_BOTH };
00215 
00216 
00217 /* Flag values for http_parser.flags field */
00218 enum flags
00219   { F_CHUNKED               = 1 << 0
00220   , F_CONNECTION_KEEP_ALIVE = 1 << 1
00221   , F_CONNECTION_CLOSE      = 1 << 2
00222   , F_CONNECTION_UPGRADE    = 1 << 3
00223   , F_TRAILING              = 1 << 4
00224   , F_UPGRADE               = 1 << 5
00225   , F_SKIPBODY              = 1 << 6
00226   , F_CONTENTLENGTH         = 1 << 7
00227   };
00228 
00229 
00230 /* Map for errno-related constants
00231  *
00232  * The provided argument should be a macro that takes 2 arguments.
00233  */
00234 #define HTTP_ERRNO_MAP(XX)                                           \
00235   /* No error */                                                     \
00236   XX(OK, "success")                                                  \
00237                                                                      \
00238   /* Callback-related errors */                                      \
00239   XX(CB_message_begin, "the on_message_begin callback failed")       \
00240   XX(CB_url, "the on_url callback failed")                           \
00241   XX(CB_header_field, "the on_header_field callback failed")         \
00242   XX(CB_header_value, "the on_header_value callback failed")         \
00243   XX(CB_headers_complete, "the on_headers_complete callback failed") \
00244   XX(CB_body, "the on_body callback failed")                         \
00245   XX(CB_message_complete, "the on_message_complete callback failed") \
00246   XX(CB_status, "the on_status callback failed")                     \
00247   XX(CB_chunk_header, "the on_chunk_header callback failed")         \
00248   XX(CB_chunk_complete, "the on_chunk_complete callback failed")     \
00249                                                                      \
00250   /* Parsing-related errors */                                       \
00251   XX(INVALID_EOF_STATE, "stream ended at an unexpected time")        \
00252   XX(HEADER_OVERFLOW,                                                \
00253      "too many header bytes seen; overflow detected")                \
00254   XX(CLOSED_CONNECTION,                                              \
00255      "data received after completed connection: close message")      \
00256   XX(INVALID_VERSION, "invalid HTTP version")                        \
00257   XX(INVALID_STATUS, "invalid HTTP status code")                     \
00258   XX(INVALID_METHOD, "invalid HTTP method")                          \
00259   XX(INVALID_URL, "invalid URL")                                     \
00260   XX(INVALID_HOST, "invalid host")                                   \
00261   XX(INVALID_PORT, "invalid port")                                   \
00262   XX(INVALID_PATH, "invalid path")                                   \
00263   XX(INVALID_QUERY_STRING, "invalid query string")                   \
00264   XX(INVALID_FRAGMENT, "invalid fragment")                           \
00265   XX(LF_EXPECTED, "LF character expected")                           \
00266   XX(INVALID_HEADER_TOKEN, "invalid character in header")            \
00267   XX(INVALID_CONTENT_LENGTH,                                         \
00268      "invalid character in content-length header")                   \
00269   XX(UNEXPECTED_CONTENT_LENGTH,                                      \
00270      "unexpected content-length header")                             \
00271   XX(INVALID_CHUNK_SIZE,                                             \
00272      "invalid character in chunk size header")                       \
00273   XX(INVALID_CONSTANT, "invalid constant string")                    \
00274   XX(INVALID_INTERNAL_STATE, "encountered unexpected internal state")\
00275   XX(STRICT, "strict mode assertion failed")                         \
00276   XX(PAUSED, "parser is paused")                                     \
00277   XX(UNKNOWN, "an unknown error occurred")
00278 
00279 
00280 /* Define HPE_* values for each errno value above */
00281 #define HTTP_ERRNO_GEN(n, s) HPE_##n,
00282 enum http_errno {
00283   HTTP_ERRNO_MAP(HTTP_ERRNO_GEN)
00284 };
00285 #undef HTTP_ERRNO_GEN
00286 
00287 
00288 /* Get an http_errno value from an http_parser */
00289 #define HTTP_PARSER_ERRNO(p)            ((enum http_errno) (p)->http_errno)
00290 
00291 
00292 struct http_parser {
00293   /** PRIVATE **/
00294   unsigned int type : 2;         /* enum http_parser_type */
00295   unsigned int flags : 8;        /* F_* values from 'flags' enum; semi-public */
00296   unsigned int state : 7;        /* enum state from http_parser.c */
00297   unsigned int header_state : 7; /* enum header_state from http_parser.c */
00298   unsigned int index : 7;        /* index into current matcher */
00299   unsigned int lenient_http_headers : 1;
00300 
00301   uint32_t nread;          /* # bytes read in various scenarios */
00302   uint64_t content_length; /* # bytes in body (0 if no Content-Length header) */
00303 
00304   /** READ-ONLY **/
00305   unsigned short http_major;
00306   unsigned short http_minor;
00307   unsigned int status_code : 16; /* responses only */
00308   unsigned int method : 8;       /* requests only */
00309   unsigned int http_errno : 7;
00310 
00311   /* 1 = Upgrade header was present and the parser has exited because of that.
00312    * 0 = No upgrade header present.
00313    * Should be checked when http_parser_execute() returns in addition to
00314    * error checking.
00315    */
00316   unsigned int upgrade : 1;
00317 
00318   /** PUBLIC **/
00319   void *data; /* A pointer to get hook to the "connection" or "socket" object */
00320 };
00321 
00322 
00323 struct http_parser_settings {
00324   http_cb      on_message_begin;
00325   http_data_cb on_url;
00326   http_data_cb on_status;
00327   http_data_cb on_header_field;
00328   http_data_cb on_header_value;
00329   http_cb      on_headers_complete;
00330   http_data_cb on_body;
00331   http_cb      on_message_complete;
00332   /* When on_chunk_header is called, the current chunk length is stored
00333    * in parser->content_length.
00334    */
00335   http_cb      on_chunk_header;
00336   http_cb      on_chunk_complete;
00337 };
00338 
00339 
00340 enum http_parser_url_fields
00341   { UF_SCHEMA           = 0
00342   , UF_HOST             = 1
00343   , UF_PORT             = 2
00344   , UF_PATH             = 3
00345   , UF_QUERY            = 4
00346   , UF_FRAGMENT         = 5
00347   , UF_USERINFO         = 6
00348   , UF_MAX              = 7
00349   };
00350 
00351 
00352 /* Result structure for http_parser_parse_url().
00353  *
00354  * Callers should index into field_data[] with UF_* values iff field_set
00355  * has the relevant (1 << UF_*) bit set. As a courtesy to clients (and
00356  * because we probably have padding left over), we convert any port to
00357  * a uint16_t.
00358  */
00359 struct http_parser_url {
00360   uint16_t field_set;           /* Bitmask of (1 << UF_*) values */
00361   uint16_t port;                /* Converted UF_PORT string */
00362 
00363   struct {
00364     uint16_t off;               /* Offset into buffer in which field starts */
00365     uint16_t len;               /* Length of run in buffer */
00366   } field_data[UF_MAX];
00367 };
00368 
00369 
00370 /* Returns the library version. Bits 16-23 contain the major version number,
00371  * bits 8-15 the minor version number and bits 0-7 the patch level.
00372  * Usage example:
00373  *
00374  *   unsigned long version = http_parser_version();
00375  *   unsigned major = (version >> 16) & 255;
00376  *   unsigned minor = (version >> 8) & 255;
00377  *   unsigned patch = version & 255;
00378  *   printf("http_parser v%u.%u.%u\n", major, minor, patch);
00379  */
00380 unsigned long http_parser_version(void);
00381 
00382 void http_parser_init(http_parser *parser, enum http_parser_type type);
00383 
00384 
00385 /* Initialize http_parser_settings members to 0
00386  */
00387 void http_parser_settings_init(http_parser_settings *settings);
00388 
00389 
00390 /* Executes the parser. Returns number of parsed bytes. Sets
00391  * `parser->http_errno` on error. */
00392 uint32_t http_parser_execute(http_parser *parser,
00393                            const http_parser_settings *settings,
00394                            const char *data,
00395                            uint32_t len);
00396 
00397 
00398 /* If http_should_keep_alive() in the on_headers_complete or
00399  * on_message_complete callback returns 0, then this should be
00400  * the last message on the connection.
00401  * If you are the server, respond with the "Connection: close" header.
00402  * If you are the client, close the connection.
00403  */
00404 int http_should_keep_alive(const http_parser *parser);
00405 
00406 /* Returns a string version of the HTTP method. */
00407 const char *http_method_str(enum http_method m);
00408 
00409 /* Return a string name of the given error */
00410 const char *http_errno_name(enum http_errno err);
00411 
00412 /* Return a string description of the given error */
00413 const char *http_errno_description(enum http_errno err);
00414 
00415 /* Initialize all http_parser_url members to 0 */
00416 void http_parser_url_init(struct http_parser_url *u);
00417 
00418 /* Parse a URL; return nonzero on failure */
00419 int http_parser_parse_url(const char *buf, uint32_t buflen,
00420                           int is_connect,
00421                           struct http_parser_url *u);
00422 
00423 /* Pause or un-pause the parser; a nonzero value pauses */
00424 void http_parser_pause(http_parser *parser, int paused);
00425 
00426 /* Checks if this is the final chunk of the body. */
00427 int http_body_is_final(const http_parser *parser);
00428 
00429 #ifdef __cplusplus
00430 }
00431 #endif
00432 #endif