chore: migrate project into clean repository

This commit is contained in:
yuuux
2026-08-13 16:50:52 +08:00
commit d1d25a09e7
27405 changed files with 9422808 additions and 0 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,8 @@
# update AUTHORS with:
# git log --all --reverse --format='%aN <%aE>' | perl -ne 'BEGIN{print "# Authors ordered by first contribution.\n"} print unless $h{$_}; $h{$_} = 1' > AUTHORS
Ryan Dahl <ry@tinyclouds.org>
Salman Haq <salman.haq@asti-usa.com>
Simon Zimmermann <simonz05@gmail.com>
Thomas LE ROUX <thomas@november-eleven.fr> LE ROUX Thomas <thomas@procheo.fr>
Thomas LE ROUX <thomas@november-eleven.fr> Thomas LE ROUX <thomas@procheo.fr>
Fedor Indutny <fedor@indutny.com>

View File

@@ -0,0 +1,13 @@
language: c
compiler:
- clang
- gcc
script:
- "make"
notifications:
email: false
irc:
- "irc.freenode.net#node-ci"

View File

@@ -0,0 +1,68 @@
# Authors ordered by first contribution.
Ryan Dahl <ry@tinyclouds.org>
Jeremy Hinegardner <jeremy@hinegardner.org>
Sergey Shepelev <temotor@gmail.com>
Joe Damato <ice799@gmail.com>
tomika <tomika_nospam@freemail.hu>
Phoenix Sol <phoenix@burninglabs.com>
Cliff Frey <cliff@meraki.com>
Ewen Cheslack-Postava <ewencp@cs.stanford.edu>
Santiago Gala <sgala@apache.org>
Tim Becker <tim.becker@syngenio.de>
Jeff Terrace <jterrace@gmail.com>
Ben Noordhuis <info@bnoordhuis.nl>
Nathan Rajlich <nathan@tootallnate.net>
Mark Nottingham <mnot@mnot.net>
Aman Gupta <aman@tmm1.net>
Tim Becker <tim.becker@kuriositaet.de>
Sean Cunningham <sean.cunningham@mandiant.com>
Peter Griess <pg@std.in>
Salman Haq <salman.haq@asti-usa.com>
Cliff Frey <clifffrey@gmail.com>
Jon Kolb <jon@b0g.us>
Fouad Mardini <f.mardini@gmail.com>
Paul Querna <pquerna@apache.org>
Felix Geisendörfer <felix@debuggable.com>
koichik <koichik@improvement.jp>
Andre Caron <andre.l.caron@gmail.com>
Ivo Raisr <ivosh@ivosh.net>
James McLaughlin <jamie@lacewing-project.org>
David Gwynne <loki@animata.net>
Thomas LE ROUX <thomas@november-eleven.fr>
Randy Rizun <rrizun@ortivawireless.com>
Andre Louis Caron <andre.louis.caron@usherbrooke.ca>
Simon Zimmermann <simonz05@gmail.com>
Erik Dubbelboer <erik@dubbelboer.com>
Martell Malone <martellmalone@gmail.com>
Bertrand Paquet <bpaquet@octo.com>
BogDan Vatra <bogdan@kde.org>
Peter Faiman <peter@thepicard.org>
Corey Richardson <corey@octayn.net>
Tóth Tamás <tomika_nospam@freemail.hu>
Cam Swords <cam.swords@gmail.com>
Chris Dickinson <christopher.s.dickinson@gmail.com>
Uli Köhler <ukoehler@btronik.de>
Charlie Somerville <charlie@charliesomerville.com>
Patrik Stutz <patrik.stutz@gmail.com>
Fedor Indutny <fedor.indutny@gmail.com>
runner <runner.mei@gmail.com>
Alexis Campailla <alexis@janeasystems.com>
David Wragg <david@wragg.org>
Vinnie Falco <vinnie.falco@gmail.com>
Alex Butum <alexbutum@linux.com>
Rex Feng <rexfeng@gmail.com>
Alex Kocharin <alex@kocharin.ru>
Mark Koopman <markmontymark@yahoo.com>
Helge Heß <me@helgehess.eu>
Alexis La Goutte <alexis.lagoutte@gmail.com>
George Miroshnykov <george.miroshnykov@gmail.com>
Maciej Małecki <me@mmalecki.com>
Marc O'Morain <github.com@marcomorain.com>
Jeff Pinner <jpinner@twitter.com>
Timothy J Fontaine <tjfontaine@gmail.com>
Akagi201 <akagi201@gmail.com>
Romain Giraud <giraud.romain@gmail.com>
Jay Satiro <raysatiro@yahoo.com>
Arne Steen <Arne.Steen@gmx.de>
Kjell Schubert <kjell.schubert@gmail.com>
Olivier Mengué <dolmen@cpan.org>

View File

@@ -0,0 +1,19 @@
Copyright Joyent, Inc. and other Node contributors.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.

View File

@@ -0,0 +1,160 @@
# Copyright Joyent, Inc. and other Node contributors. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
PLATFORM ?= $(shell sh -c 'uname -s | tr "[A-Z]" "[a-z]"')
HELPER ?=
BINEXT ?=
SOLIBNAME = libhttp_parser
SOMAJOR = 2
SOMINOR = 9
SOREV = 4
ifeq (darwin,$(PLATFORM))
SOEXT ?= dylib
SONAME ?= $(SOLIBNAME).$(SOMAJOR).$(SOMINOR).$(SOEXT)
LIBNAME ?= $(SOLIBNAME).$(SOMAJOR).$(SOMINOR).$(SOREV).$(SOEXT)
else ifeq (wine,$(PLATFORM))
CC = winegcc
BINEXT = .exe.so
HELPER = wine
else
SOEXT ?= so
SONAME ?= $(SOLIBNAME).$(SOEXT).$(SOMAJOR).$(SOMINOR)
LIBNAME ?= $(SOLIBNAME).$(SOEXT).$(SOMAJOR).$(SOMINOR).$(SOREV)
endif
CC?=gcc
AR?=ar
CPPFLAGS ?=
LDFLAGS ?=
CPPFLAGS += -I.
CPPFLAGS_DEBUG = $(CPPFLAGS) -DHTTP_PARSER_STRICT=1
CPPFLAGS_DEBUG += $(CPPFLAGS_DEBUG_EXTRA)
CPPFLAGS_FAST = $(CPPFLAGS) -DHTTP_PARSER_STRICT=0
CPPFLAGS_FAST += $(CPPFLAGS_FAST_EXTRA)
CPPFLAGS_BENCH = $(CPPFLAGS_FAST)
CFLAGS += -Wall -Wextra -Werror
CFLAGS_DEBUG = $(CFLAGS) -O0 -g $(CFLAGS_DEBUG_EXTRA)
CFLAGS_FAST = $(CFLAGS) -O3 $(CFLAGS_FAST_EXTRA)
CFLAGS_BENCH = $(CFLAGS_FAST) -Wno-unused-parameter
CFLAGS_LIB = $(CFLAGS_FAST) -fPIC
LDFLAGS_LIB = $(LDFLAGS) -shared
INSTALL ?= install
PREFIX ?= /usr/local
LIBDIR = $(PREFIX)/lib
INCLUDEDIR = $(PREFIX)/include
ifeq (darwin,$(PLATFORM))
LDFLAGS_LIB += -Wl,-install_name,$(LIBDIR)/$(SONAME)
else
# TODO(bnoordhuis) The native SunOS linker expects -h rather than -soname...
LDFLAGS_LIB += -Wl,-soname=$(SONAME)
endif
test: test_g test_fast
$(HELPER) ./test_g$(BINEXT)
$(HELPER) ./test_fast$(BINEXT)
test_g: http_parser_g.o test_g.o
$(CC) $(CFLAGS_DEBUG) $(LDFLAGS) http_parser_g.o test_g.o -o $@
test_g.o: test.c http_parser.h Makefile
$(CC) $(CPPFLAGS_DEBUG) $(CFLAGS_DEBUG) -c test.c -o $@
http_parser_g.o: http_parser.c http_parser.h Makefile
$(CC) $(CPPFLAGS_DEBUG) $(CFLAGS_DEBUG) -c http_parser.c -o $@
test_fast: http_parser.o test.o http_parser.h
$(CC) $(CFLAGS_FAST) $(LDFLAGS) http_parser.o test.o -o $@
test.o: test.c http_parser.h Makefile
$(CC) $(CPPFLAGS_FAST) $(CFLAGS_FAST) -c test.c -o $@
bench: http_parser.o bench.o
$(CC) $(CFLAGS_BENCH) $(LDFLAGS) http_parser.o bench.o -o $@
bench.o: bench.c http_parser.h Makefile
$(CC) $(CPPFLAGS_BENCH) $(CFLAGS_BENCH) -c bench.c -o $@
http_parser.o: http_parser.c http_parser.h Makefile
$(CC) $(CPPFLAGS_FAST) $(CFLAGS_FAST) -c http_parser.c
test-run-timed: test_fast
while(true) do time $(HELPER) ./test_fast$(BINEXT) > /dev/null; done
test-valgrind: test_g
valgrind ./test_g
libhttp_parser.o: http_parser.c http_parser.h Makefile
$(CC) $(CPPFLAGS_FAST) $(CFLAGS_LIB) -c http_parser.c -o libhttp_parser.o
library: libhttp_parser.o
$(CC) $(LDFLAGS_LIB) -o $(LIBNAME) $<
package: http_parser.o
$(AR) rcs libhttp_parser.a http_parser.o
url_parser: http_parser.o contrib/url_parser.c
$(CC) $(CPPFLAGS_FAST) $(CFLAGS_FAST) $^ -o $@
url_parser_g: http_parser_g.o contrib/url_parser.c
$(CC) $(CPPFLAGS_DEBUG) $(CFLAGS_DEBUG) $^ -o $@
parsertrace: http_parser.o contrib/parsertrace.c
$(CC) $(CPPFLAGS_FAST) $(CFLAGS_FAST) $^ -o parsertrace$(BINEXT)
parsertrace_g: http_parser_g.o contrib/parsertrace.c
$(CC) $(CPPFLAGS_DEBUG) $(CFLAGS_DEBUG) $^ -o parsertrace_g$(BINEXT)
tags: http_parser.c http_parser.h test.c
ctags $^
install: library
$(INSTALL) -D http_parser.h $(DESTDIR)$(INCLUDEDIR)/http_parser.h
$(INSTALL) -D $(LIBNAME) $(DESTDIR)$(LIBDIR)/$(LIBNAME)
ln -sf $(LIBNAME) $(DESTDIR)$(LIBDIR)/$(SONAME)
ln -sf $(LIBNAME) $(DESTDIR)$(LIBDIR)/$(SOLIBNAME).$(SOEXT)
install-strip: library
$(INSTALL) -D http_parser.h $(DESTDIR)$(INCLUDEDIR)/http_parser.h
$(INSTALL) -D -s $(LIBNAME) $(DESTDIR)$(LIBDIR)/$(LIBNAME)
ln -sf $(LIBNAME) $(DESTDIR)$(LIBDIR)/$(SONAME)
ln -sf $(LIBNAME) $(DESTDIR)$(LIBDIR)/$(SOLIBNAME).$(SOEXT)
uninstall:
rm $(DESTDIR)$(INCLUDEDIR)/http_parser.h
rm $(DESTDIR)$(LIBDIR)/$(SOLIBNAME).$(SOEXT)
rm $(DESTDIR)$(LIBDIR)/$(SONAME)
rm $(DESTDIR)$(LIBDIR)/$(LIBNAME)
clean:
rm -f *.o *.a tags test test_fast test_g \
http_parser.tar libhttp_parser.so.* \
url_parser url_parser_g parsertrace parsertrace_g \
*.exe *.exe.so
contrib/url_parser.c: http_parser.h
contrib/parsertrace.c: http_parser.h
.PHONY: clean package test-run test-run-timed test-valgrind install install-strip uninstall

View File

@@ -0,0 +1,249 @@
HTTP Parser
===========
http-parser is [**not** actively maintained](https://github.com/nodejs/http-parser/issues/522).
New projects and projects looking to migrate should consider [llhttp](https://github.com/nodejs/llhttp).
[![Build Status](https://api.travis-ci.org/nodejs/http-parser.svg?branch=master)](https://travis-ci.org/nodejs/http-parser)
This is a parser for HTTP messages written in C. It parses both requests and
responses. The parser is designed to be used in performance HTTP
applications. It does not make any syscalls nor allocations, it does not
buffer data, it can be interrupted at anytime. Depending on your
architecture, it only requires about 40 bytes of data per message
stream (in a web server that is per connection).
Features:
* No dependencies
* Handles persistent streams (keep-alive).
* Decodes chunked encoding.
* Upgrade support
* Defends against buffer overflow attacks.
The parser extracts the following information from HTTP messages:
* Header fields and values
* Content-Length
* Request method
* Response status code
* Transfer-Encoding
* HTTP version
* Request URL
* Message body
Usage
-----
One `http_parser` object is used per TCP connection. Initialize the struct
using `http_parser_init()` and set the callbacks. That might look something
like this for a request parser:
```c
http_parser_settings settings;
settings.on_url = my_url_callback;
settings.on_header_field = my_header_field_callback;
/* ... */
http_parser *parser = malloc(sizeof(http_parser));
http_parser_init(parser, HTTP_REQUEST);
parser->data = my_socket;
```
When data is received on the socket execute the parser and check for errors.
```c
size_t len = 80*1024, nparsed;
char buf[len];
ssize_t recved;
recved = recv(fd, buf, len, 0);
if (recved < 0) {
/* Handle error. */
}
/* Start up / continue the parser.
* Note we pass recved==0 to signal that EOF has been received.
*/
nparsed = http_parser_execute(parser, &settings, buf, recved);
if (parser->upgrade) {
/* handle new protocol */
} else if (nparsed != recved) {
/* Handle error. Usually just close the connection. */
}
```
`http_parser` needs to know where the end of the stream is. For example, sometimes
servers send responses without Content-Length and expect the client to
consume input (for the body) until EOF. To tell `http_parser` about EOF, give
`0` as the fourth parameter to `http_parser_execute()`. Callbacks and errors
can still be encountered during an EOF, so one must still be prepared
to receive them.
Scalar valued message information such as `status_code`, `method`, and the
HTTP version are stored in the parser structure. This data is only
temporally stored in `http_parser` and gets reset on each new message. If
this information is needed later, copy it out of the structure during the
`headers_complete` callback.
The parser decodes the transfer-encoding for both requests and responses
transparently. That is, a chunked encoding is decoded before being sent to
the on_body callback.
The Special Problem of Upgrade
------------------------------
`http_parser` supports upgrading the connection to a different protocol. An
increasingly common example of this is the WebSocket protocol which sends
a request like
GET /demo HTTP/1.1
Upgrade: WebSocket
Connection: Upgrade
Host: example.com
Origin: http://example.com
WebSocket-Protocol: sample
followed by non-HTTP data.
(See [RFC6455](https://tools.ietf.org/html/rfc6455) for more information the
WebSocket protocol.)
To support this, the parser will treat this as a normal HTTP message without a
body, issuing both on_headers_complete and on_message_complete callbacks. However
http_parser_execute() will stop parsing at the end of the headers and return.
The user is expected to check if `parser->upgrade` has been set to 1 after
`http_parser_execute()` returns. Non-HTTP data begins at the buffer supplied
offset by the return value of `http_parser_execute()`.
Callbacks
---------
During the `http_parser_execute()` call, the callbacks set in
`http_parser_settings` will be executed. The parser maintains state and
never looks behind, so buffering the data is not necessary. If you need to
save certain data for later usage, you can do that from the callbacks.
There are two types of callbacks:
* notification `typedef int (*http_cb) (http_parser*);`
Callbacks: on_message_begin, on_headers_complete, on_message_complete.
* data `typedef int (*http_data_cb) (http_parser*, const char *at, size_t length);`
Callbacks: (requests only) on_url,
(common) on_header_field, on_header_value, on_body;
Callbacks must return 0 on success. Returning a non-zero value indicates
error to the parser, making it exit immediately.
For cases where it is necessary to pass local information to/from a callback,
the `http_parser` object's `data` field can be used.
An example of such a case is when using threads to handle a socket connection,
parse a request, and then give a response over that socket. By instantiation
of a thread-local struct containing relevant data (e.g. accepted socket,
allocated memory for callbacks to write into, etc), a parser's callbacks are
able to communicate data between the scope of the thread and the scope of the
callback in a threadsafe manner. This allows `http_parser` to be used in
multi-threaded contexts.
Example:
```c
typedef struct {
socket_t sock;
void* buffer;
int buf_len;
} custom_data_t;
int my_url_callback(http_parser* parser, const char *at, size_t length) {
/* access to thread local custom_data_t struct.
Use this access save parsed data for later use into thread local
buffer, or communicate over socket
*/
parser->data;
...
return 0;
}
...
void http_parser_thread(socket_t sock) {
int nparsed = 0;
/* allocate memory for user data */
custom_data_t *my_data = malloc(sizeof(custom_data_t));
/* some information for use by callbacks.
* achieves thread -> callback information flow */
my_data->sock = sock;
/* instantiate a thread-local parser */
http_parser *parser = malloc(sizeof(http_parser));
http_parser_init(parser, HTTP_REQUEST); /* initialise parser */
/* this custom data reference is accessible through the reference to the
parser supplied to callback functions */
parser->data = my_data;
http_parser_settings settings; /* set up callbacks */
settings.on_url = my_url_callback;
/* execute parser */
nparsed = http_parser_execute(parser, &settings, buf, recved);
...
/* parsed information copied from callback.
can now perform action on data copied into thread-local memory from callbacks.
achieves callback -> thread information flow */
my_data->buffer;
...
}
```
In case you parse HTTP message in chunks (i.e. `read()` request line
from socket, parse, read half headers, parse, etc) your data callbacks
may be called more than once. `http_parser` guarantees that data pointer is only
valid for the lifetime of callback. You can also `read()` into a heap allocated
buffer to avoid copying memory around if this fits your application.
Reading headers may be a tricky task if you read/parse headers partially.
Basically, you need to remember whether last header callback was field or value
and apply the following logic:
(on_header_field and on_header_value shortened to on_h_*)
------------------------ ------------ --------------------------------------------
| State (prev. callback) | Callback | Description/action |
------------------------ ------------ --------------------------------------------
| nothing (first call) | on_h_field | Allocate new buffer and copy callback data |
| | | into it |
------------------------ ------------ --------------------------------------------
| value | on_h_field | New header started. |
| | | Copy current name,value buffers to headers |
| | | list and allocate new buffer for new name |
------------------------ ------------ --------------------------------------------
| field | on_h_field | Previous name continues. Reallocate name |
| | | buffer and append callback data to it |
------------------------ ------------ --------------------------------------------
| field | on_h_value | Value for current header started. Allocate |
| | | new buffer and copy callback data to it |
------------------------ ------------ --------------------------------------------
| value | on_h_value | Value continues. Reallocate value buffer |
| | | and append callback data to it |
------------------------ ------------ --------------------------------------------
Parsing URLs
------------
A simplistic zero-copy URL parser is provided as `http_parser_parse_url()`.
Users of this library may wish to use it to parse URLs constructed from
consecutive `on_url` callbacks.
See examples of reading in headers:
* [partial example](http://gist.github.com/155877) in C
* [from http-parser tests](http://github.com/joyent/http-parser/blob/37a0ff8/test.c#L403) in C
* [from Node library](http://github.com/joyent/node/blob/842eaf4/src/http.js#L284) in Javascript

View File

@@ -0,0 +1,128 @@
/* Copyright Fedor Indutny. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include "http_parser.h"
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
/* 8 gb */
static const int64_t kBytes = 8LL << 30;
static const char data[] =
"POST /joyent/http-parser HTTP/1.1\r\n"
"Host: github.com\r\n"
"DNT: 1\r\n"
"Accept-Encoding: gzip, deflate, sdch\r\n"
"Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4\r\n"
"User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/39.0.2171.65 Safari/537.36\r\n"
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,"
"image/webp,*/*;q=0.8\r\n"
"Referer: https://github.com/joyent/http-parser\r\n"
"Connection: keep-alive\r\n"
"Transfer-Encoding: chunked\r\n"
"Cache-Control: max-age=0\r\n\r\nb\r\nhello world\r\n0\r\n";
static const size_t data_len = sizeof(data) - 1;
static int on_info(http_parser* p) {
return 0;
}
static int on_data(http_parser* p, const char *at, size_t length) {
return 0;
}
static http_parser_settings settings = {
.on_message_begin = on_info,
.on_headers_complete = on_info,
.on_message_complete = on_info,
.on_header_field = on_data,
.on_header_value = on_data,
.on_url = on_data,
.on_status = on_data,
.on_body = on_data
};
int bench(int iter_count, int silent) {
struct http_parser parser;
int i;
int err;
struct timeval start;
struct timeval end;
if (!silent) {
err = gettimeofday(&start, NULL);
assert(err == 0);
}
fprintf(stderr, "req_len=%d\n", (int) data_len);
for (i = 0; i < iter_count; i++) {
size_t parsed;
http_parser_init(&parser, HTTP_REQUEST);
parsed = http_parser_execute(&parser, &settings, data, data_len);
assert(parsed == data_len);
}
if (!silent) {
double elapsed;
double bw;
double total;
err = gettimeofday(&end, NULL);
assert(err == 0);
fprintf(stdout, "Benchmark result:\n");
elapsed = (double) (end.tv_sec - start.tv_sec) +
(end.tv_usec - start.tv_usec) * 1e-6f;
total = (double) iter_count * data_len;
bw = (double) total / elapsed;
fprintf(stdout, "%.2f mb | %.2f mb/s | %.2f req/sec | %.2f s\n",
(double) total / (1024 * 1024),
bw / (1024 * 1024),
(double) iter_count / elapsed,
elapsed);
fflush(stdout);
}
return 0;
}
int main(int argc, char** argv) {
int64_t iterations;
iterations = kBytes / (int64_t) data_len;
if (argc == 2 && strcmp(argv[1], "infinite") == 0) {
for (;;)
bench(iterations, 1);
return 0;
} else {
return bench(iterations, 0);
}
}

View File

@@ -0,0 +1,157 @@
/* Copyright Joyent, Inc. and other Node contributors.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
/* Dump what the parser finds to stdout as it happen */
#include "http_parser.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int on_message_begin(http_parser* _) {
(void)_;
printf("\n***MESSAGE BEGIN***\n\n");
return 0;
}
int on_headers_complete(http_parser* _) {
(void)_;
printf("\n***HEADERS COMPLETE***\n\n");
return 0;
}
int on_message_complete(http_parser* _) {
(void)_;
printf("\n***MESSAGE COMPLETE***\n\n");
return 0;
}
int on_url(http_parser* _, const char* at, size_t length) {
(void)_;
printf("Url: %.*s\n", (int)length, at);
return 0;
}
int on_header_field(http_parser* _, const char* at, size_t length) {
(void)_;
printf("Header field: %.*s\n", (int)length, at);
return 0;
}
int on_header_value(http_parser* _, const char* at, size_t length) {
(void)_;
printf("Header value: %.*s\n", (int)length, at);
return 0;
}
int on_body(http_parser* _, const char* at, size_t length) {
(void)_;
printf("Body: %.*s\n", (int)length, at);
return 0;
}
void usage(const char* name) {
fprintf(stderr,
"Usage: %s $type $filename\n"
" type: -x, where x is one of {r,b,q}\n"
" parses file as a Response, reQuest, or Both\n",
name);
exit(EXIT_FAILURE);
}
int main(int argc, char* argv[]) {
enum http_parser_type file_type;
if (argc != 3) {
usage(argv[0]);
}
char* type = argv[1];
if (type[0] != '-') {
usage(argv[0]);
}
switch (type[1]) {
/* in the case of "-", type[1] will be NUL */
case 'r':
file_type = HTTP_RESPONSE;
break;
case 'q':
file_type = HTTP_REQUEST;
break;
case 'b':
file_type = HTTP_BOTH;
break;
default:
usage(argv[0]);
}
char* filename = argv[2];
FILE* file = fopen(filename, "r");
if (file == NULL) {
perror("fopen");
goto fail;
}
fseek(file, 0, SEEK_END);
long file_length = ftell(file);
if (file_length == -1) {
perror("ftell");
goto fail;
}
fseek(file, 0, SEEK_SET);
char* data = malloc(file_length);
if (fread(data, 1, file_length, file) != (size_t)file_length) {
fprintf(stderr, "couldn't read entire file\n");
free(data);
goto fail;
}
http_parser_settings settings;
memset(&settings, 0, sizeof(settings));
settings.on_message_begin = on_message_begin;
settings.on_url = on_url;
settings.on_header_field = on_header_field;
settings.on_header_value = on_header_value;
settings.on_headers_complete = on_headers_complete;
settings.on_body = on_body;
settings.on_message_complete = on_message_complete;
http_parser parser;
http_parser_init(&parser, file_type);
size_t nparsed = http_parser_execute(&parser, &settings, data, file_length);
free(data);
if (nparsed != (size_t)file_length) {
fprintf(stderr,
"Error: %s (%s)\n",
http_errno_description(HTTP_PARSER_ERRNO(&parser)),
http_errno_name(HTTP_PARSER_ERRNO(&parser)));
goto fail;
}
return EXIT_SUCCESS;
fail:
fclose(file);
return EXIT_FAILURE;
}

View File

@@ -0,0 +1,47 @@
#include "http_parser.h"
#include <stdio.h>
#include <string.h>
void
dump_url (const char *url, const struct http_parser_url *u)
{
unsigned int i;
printf("\tfield_set: 0x%x, port: %u\n", u->field_set, u->port);
for (i = 0; i < UF_MAX; i++) {
if ((u->field_set & (1 << i)) == 0) {
printf("\tfield_data[%u]: unset\n", i);
continue;
}
printf("\tfield_data[%u]: off: %u, len: %u, part: %.*s\n",
i,
u->field_data[i].off,
u->field_data[i].len,
u->field_data[i].len,
url + u->field_data[i].off);
}
}
int main(int argc, char ** argv) {
struct http_parser_url u;
int len, connect, result;
if (argc != 3) {
printf("Syntax : %s connect|get url\n", argv[0]);
return 1;
}
len = strlen(argv[2]);
connect = strcmp("connect", argv[1]) == 0 ? 1 : 0;
printf("Parsing %s, connect %d\n", argv[2], connect);
http_parser_url_init(&u);
result = http_parser_parse_url(argv[2], len, connect, &u);
if (result != 0) {
printf("Parse error : %d\n", result);
return result;
}
printf("Parse ok, result : \n");
dump_url(argv[2], &u);
return 0;
}

View File

@@ -0,0 +1,26 @@
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "http_parser.h"
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
{
static const http_parser_settings settings_null = {
.on_message_begin = 0
, .on_header_field = 0
,.on_header_value = 0
,.on_url = 0
,.on_status = 0
,.on_body = 0
,.on_headers_complete = 0
,.on_message_complete = 0
,.on_chunk_header = 0
,.on_chunk_complete = 0
};
http_parser parser;
http_parser_init(&parser, HTTP_BOTH);
http_parser_execute(&parser, &settings_null, (char*)data, size);
return 0;
}

View File

@@ -0,0 +1,14 @@
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "http_parser.h"
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
{
struct http_parser_url u;
http_parser_url_init(&u);
http_parser_parse_url((char*)data, size, 0, &u);
http_parser_parse_url((char*)data, size, 1, &u);
return 0;
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,111 @@
# This file is used with the GYP meta build system.
# http://code.google.com/p/gyp/
# To build try this:
# svn co http://gyp.googlecode.com/svn/trunk gyp
# ./gyp/gyp -f make --depth=`pwd` http_parser.gyp
# ./out/Debug/test
{
'target_defaults': {
'default_configuration': 'Debug',
'configurations': {
# TODO: hoist these out and put them somewhere common, because
# RuntimeLibrary MUST MATCH across the entire project
'Debug': {
'defines': [ 'DEBUG', '_DEBUG' ],
'cflags': [ '-Wall', '-Wextra', '-O0', '-g', '-ftrapv' ],
'msvs_settings': {
'VCCLCompilerTool': {
'RuntimeLibrary': 1, # static debug
},
},
},
'Release': {
'defines': [ 'NDEBUG' ],
'cflags': [ '-Wall', '-Wextra', '-O3' ],
'msvs_settings': {
'VCCLCompilerTool': {
'RuntimeLibrary': 0, # static release
},
},
}
},
'msvs_settings': {
'VCCLCompilerTool': {
},
'VCLibrarianTool': {
},
'VCLinkerTool': {
'GenerateDebugInformation': 'true',
},
},
'conditions': [
['OS == "win"', {
'defines': [
'WIN32'
],
}]
],
},
'targets': [
{
'target_name': 'http_parser',
'type': 'static_library',
'include_dirs': [ '.' ],
'direct_dependent_settings': {
'defines': [ 'HTTP_PARSER_STRICT=0' ],
'include_dirs': [ '.' ],
},
'defines': [ 'HTTP_PARSER_STRICT=0' ],
'sources': [ './http_parser.c', ],
'conditions': [
['OS=="win"', {
'msvs_settings': {
'VCCLCompilerTool': {
# Compile as C++. http_parser.c is actually C99, but C++ is
# close enough in this case.
'CompileAs': 2,
},
},
}]
],
},
{
'target_name': 'http_parser_strict',
'type': 'static_library',
'include_dirs': [ '.' ],
'direct_dependent_settings': {
'defines': [ 'HTTP_PARSER_STRICT=1' ],
'include_dirs': [ '.' ],
},
'defines': [ 'HTTP_PARSER_STRICT=1' ],
'sources': [ './http_parser.c', ],
'conditions': [
['OS=="win"', {
'msvs_settings': {
'VCCLCompilerTool': {
# Compile as C++. http_parser.c is actually C99, but C++ is
# close enough in this case.
'CompileAs': 2,
},
},
}]
],
},
{
'target_name': 'test-nonstrict',
'type': 'executable',
'dependencies': [ 'http_parser' ],
'sources': [ 'test.c' ]
},
{
'target_name': 'test-strict',
'type': 'executable',
'dependencies': [ 'http_parser_strict' ],
'sources': [ 'test.c' ]
}
]
}

View File

@@ -0,0 +1,449 @@
/* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#ifndef http_parser_h
#define http_parser_h
#ifdef __cplusplus
extern "C" {
#endif
/* Also update SONAME in the Makefile whenever you change these. */
#define HTTP_PARSER_VERSION_MAJOR 2
#define HTTP_PARSER_VERSION_MINOR 9
#define HTTP_PARSER_VERSION_PATCH 4
#include <stddef.h>
#if defined(_WIN32) && !defined(__MINGW32__) && \
(!defined(_MSC_VER) || _MSC_VER<1600) && !defined(__WINE__)
#include <BaseTsd.h>
typedef __int8 int8_t;
typedef unsigned __int8 uint8_t;
typedef __int16 int16_t;
typedef unsigned __int16 uint16_t;
typedef __int32 int32_t;
typedef unsigned __int32 uint32_t;
typedef __int64 int64_t;
typedef unsigned __int64 uint64_t;
#elif (defined(__sun) || defined(__sun__)) && defined(__SunOS_5_9)
#include <sys/inttypes.h>
#else
#include <stdint.h>
#endif
/* Compile with -DHTTP_PARSER_STRICT=0 to make less checks, but run
* faster
*/
#ifndef HTTP_PARSER_STRICT
# define HTTP_PARSER_STRICT 1
#endif
/* Maximium header size allowed. If the macro is not defined
* before including this header then the default is used. To
* change the maximum header size, define the macro in the build
* environment (e.g. -DHTTP_MAX_HEADER_SIZE=<value>). To remove
* the effective limit on the size of the header, define the macro
* to a very large number (e.g. -DHTTP_MAX_HEADER_SIZE=0x7fffffff)
*/
#ifndef HTTP_MAX_HEADER_SIZE
# define HTTP_MAX_HEADER_SIZE (80*1024)
#endif
typedef struct http_parser http_parser;
typedef struct http_parser_settings http_parser_settings;
/* Callbacks should return non-zero to indicate an error. The parser will
* then halt execution.
*
* The one exception is on_headers_complete. In a HTTP_RESPONSE parser
* returning '1' from on_headers_complete will tell the parser that it
* should not expect a body. This is used when receiving a response to a
* HEAD request which may contain 'Content-Length' or 'Transfer-Encoding:
* chunked' headers that indicate the presence of a body.
*
* Returning `2` from on_headers_complete will tell parser that it should not
* expect neither a body nor any futher responses on this connection. This is
* useful for handling responses to a CONNECT request which may not contain
* `Upgrade` or `Connection: upgrade` headers.
*
* http_data_cb does not return data chunks. It will be called arbitrarily
* many times for each string. E.G. you might get 10 callbacks for "on_url"
* each providing just a few characters more data.
*/
typedef int (*http_data_cb) (http_parser*, const char *at, size_t length);
typedef int (*http_cb) (http_parser*);
/* Status Codes */
#define HTTP_STATUS_MAP(XX) \
XX(100, CONTINUE, Continue) \
XX(101, SWITCHING_PROTOCOLS, Switching Protocols) \
XX(102, PROCESSING, Processing) \
XX(200, OK, OK) \
XX(201, CREATED, Created) \
XX(202, ACCEPTED, Accepted) \
XX(203, NON_AUTHORITATIVE_INFORMATION, Non-Authoritative Information) \
XX(204, NO_CONTENT, No Content) \
XX(205, RESET_CONTENT, Reset Content) \
XX(206, PARTIAL_CONTENT, Partial Content) \
XX(207, MULTI_STATUS, Multi-Status) \
XX(208, ALREADY_REPORTED, Already Reported) \
XX(226, IM_USED, IM Used) \
XX(300, MULTIPLE_CHOICES, Multiple Choices) \
XX(301, MOVED_PERMANENTLY, Moved Permanently) \
XX(302, FOUND, Found) \
XX(303, SEE_OTHER, See Other) \
XX(304, NOT_MODIFIED, Not Modified) \
XX(305, USE_PROXY, Use Proxy) \
XX(307, TEMPORARY_REDIRECT, Temporary Redirect) \
XX(308, PERMANENT_REDIRECT, Permanent Redirect) \
XX(400, BAD_REQUEST, Bad Request) \
XX(401, UNAUTHORIZED, Unauthorized) \
XX(402, PAYMENT_REQUIRED, Payment Required) \
XX(403, FORBIDDEN, Forbidden) \
XX(404, NOT_FOUND, Not Found) \
XX(405, METHOD_NOT_ALLOWED, Method Not Allowed) \
XX(406, NOT_ACCEPTABLE, Not Acceptable) \
XX(407, PROXY_AUTHENTICATION_REQUIRED, Proxy Authentication Required) \
XX(408, REQUEST_TIMEOUT, Request Timeout) \
XX(409, CONFLICT, Conflict) \
XX(410, GONE, Gone) \
XX(411, LENGTH_REQUIRED, Length Required) \
XX(412, PRECONDITION_FAILED, Precondition Failed) \
XX(413, PAYLOAD_TOO_LARGE, Payload Too Large) \
XX(414, URI_TOO_LONG, URI Too Long) \
XX(415, UNSUPPORTED_MEDIA_TYPE, Unsupported Media Type) \
XX(416, RANGE_NOT_SATISFIABLE, Range Not Satisfiable) \
XX(417, EXPECTATION_FAILED, Expectation Failed) \
XX(421, MISDIRECTED_REQUEST, Misdirected Request) \
XX(422, UNPROCESSABLE_ENTITY, Unprocessable Entity) \
XX(423, LOCKED, Locked) \
XX(424, FAILED_DEPENDENCY, Failed Dependency) \
XX(426, UPGRADE_REQUIRED, Upgrade Required) \
XX(428, PRECONDITION_REQUIRED, Precondition Required) \
XX(429, TOO_MANY_REQUESTS, Too Many Requests) \
XX(431, REQUEST_HEADER_FIELDS_TOO_LARGE, Request Header Fields Too Large) \
XX(451, UNAVAILABLE_FOR_LEGAL_REASONS, Unavailable For Legal Reasons) \
XX(500, INTERNAL_SERVER_ERROR, Internal Server Error) \
XX(501, NOT_IMPLEMENTED, Not Implemented) \
XX(502, BAD_GATEWAY, Bad Gateway) \
XX(503, SERVICE_UNAVAILABLE, Service Unavailable) \
XX(504, GATEWAY_TIMEOUT, Gateway Timeout) \
XX(505, HTTP_VERSION_NOT_SUPPORTED, HTTP Version Not Supported) \
XX(506, VARIANT_ALSO_NEGOTIATES, Variant Also Negotiates) \
XX(507, INSUFFICIENT_STORAGE, Insufficient Storage) \
XX(508, LOOP_DETECTED, Loop Detected) \
XX(510, NOT_EXTENDED, Not Extended) \
XX(511, NETWORK_AUTHENTICATION_REQUIRED, Network Authentication Required) \
enum http_status
{
#define XX(num, name, string) HTTP_STATUS_##name = num,
HTTP_STATUS_MAP(XX)
#undef XX
};
/* Request Methods */
#define HTTP_METHOD_MAP(XX) \
XX(0, DELETE, DELETE) \
XX(1, GET, GET) \
XX(2, HEAD, HEAD) \
XX(3, POST, POST) \
XX(4, PUT, PUT) \
/* pathological */ \
XX(5, CONNECT, CONNECT) \
XX(6, OPTIONS, OPTIONS) \
XX(7, TRACE, TRACE) \
/* WebDAV */ \
XX(8, COPY, COPY) \
XX(9, LOCK, LOCK) \
XX(10, MKCOL, MKCOL) \
XX(11, MOVE, MOVE) \
XX(12, PROPFIND, PROPFIND) \
XX(13, PROPPATCH, PROPPATCH) \
XX(14, SEARCH, SEARCH) \
XX(15, UNLOCK, UNLOCK) \
XX(16, BIND, BIND) \
XX(17, REBIND, REBIND) \
XX(18, UNBIND, UNBIND) \
XX(19, ACL, ACL) \
/* subversion */ \
XX(20, REPORT, REPORT) \
XX(21, MKACTIVITY, MKACTIVITY) \
XX(22, CHECKOUT, CHECKOUT) \
XX(23, MERGE, MERGE) \
/* upnp */ \
XX(24, MSEARCH, M-SEARCH) \
XX(25, NOTIFY, NOTIFY) \
XX(26, SUBSCRIBE, SUBSCRIBE) \
XX(27, UNSUBSCRIBE, UNSUBSCRIBE) \
/* RFC-5789 */ \
XX(28, PATCH, PATCH) \
XX(29, PURGE, PURGE) \
/* CalDAV */ \
XX(30, MKCALENDAR, MKCALENDAR) \
/* RFC-2068, section 19.6.1.2 */ \
XX(31, LINK, LINK) \
XX(32, UNLINK, UNLINK) \
/* icecast */ \
XX(33, SOURCE, SOURCE) \
enum http_method
{
#define XX(num, name, string) HTTP_##name = num,
HTTP_METHOD_MAP(XX)
#undef XX
};
enum http_parser_type { HTTP_REQUEST, HTTP_RESPONSE, HTTP_BOTH };
/* Flag values for http_parser.flags field */
enum flags
{ F_CHUNKED = 1 << 0
, F_CONNECTION_KEEP_ALIVE = 1 << 1
, F_CONNECTION_CLOSE = 1 << 2
, F_CONNECTION_UPGRADE = 1 << 3
, F_TRAILING = 1 << 4
, F_UPGRADE = 1 << 5
, F_SKIPBODY = 1 << 6
, F_CONTENTLENGTH = 1 << 7
};
/* Map for errno-related constants
*
* The provided argument should be a macro that takes 2 arguments.
*/
#define HTTP_ERRNO_MAP(XX) \
/* No error */ \
XX(OK, "success") \
\
/* Callback-related errors */ \
XX(CB_message_begin, "the on_message_begin callback failed") \
XX(CB_url, "the on_url callback failed") \
XX(CB_header_field, "the on_header_field callback failed") \
XX(CB_header_value, "the on_header_value callback failed") \
XX(CB_headers_complete, "the on_headers_complete callback failed") \
XX(CB_body, "the on_body callback failed") \
XX(CB_message_complete, "the on_message_complete callback failed") \
XX(CB_status, "the on_status callback failed") \
XX(CB_chunk_header, "the on_chunk_header callback failed") \
XX(CB_chunk_complete, "the on_chunk_complete callback failed") \
\
/* Parsing-related errors */ \
XX(INVALID_EOF_STATE, "stream ended at an unexpected time") \
XX(HEADER_OVERFLOW, \
"too many header bytes seen; overflow detected") \
XX(CLOSED_CONNECTION, \
"data received after completed connection: close message") \
XX(INVALID_VERSION, "invalid HTTP version") \
XX(INVALID_STATUS, "invalid HTTP status code") \
XX(INVALID_METHOD, "invalid HTTP method") \
XX(INVALID_URL, "invalid URL") \
XX(INVALID_HOST, "invalid host") \
XX(INVALID_PORT, "invalid port") \
XX(INVALID_PATH, "invalid path") \
XX(INVALID_QUERY_STRING, "invalid query string") \
XX(INVALID_FRAGMENT, "invalid fragment") \
XX(LF_EXPECTED, "LF character expected") \
XX(INVALID_HEADER_TOKEN, "invalid character in header") \
XX(INVALID_CONTENT_LENGTH, \
"invalid character in content-length header") \
XX(UNEXPECTED_CONTENT_LENGTH, \
"unexpected content-length header") \
XX(INVALID_CHUNK_SIZE, \
"invalid character in chunk size header") \
XX(INVALID_CONSTANT, "invalid constant string") \
XX(INVALID_INTERNAL_STATE, "encountered unexpected internal state")\
XX(STRICT, "strict mode assertion failed") \
XX(PAUSED, "parser is paused") \
XX(UNKNOWN, "an unknown error occurred") \
XX(INVALID_TRANSFER_ENCODING, \
"request has invalid transfer-encoding") \
/* Define HPE_* values for each errno value above */
#define HTTP_ERRNO_GEN(n, s) HPE_##n,
enum http_errno {
HTTP_ERRNO_MAP(HTTP_ERRNO_GEN)
};
#undef HTTP_ERRNO_GEN
/* Get an http_errno value from an http_parser */
#define HTTP_PARSER_ERRNO(p) ((enum http_errno) (p)->http_errno)
struct http_parser {
/** PRIVATE **/
unsigned int type : 2; /* enum http_parser_type */
unsigned int flags : 8; /* F_* values from 'flags' enum; semi-public */
unsigned int state : 7; /* enum state from http_parser.c */
unsigned int header_state : 7; /* enum header_state from http_parser.c */
unsigned int index : 5; /* index into current matcher */
unsigned int uses_transfer_encoding : 1; /* Transfer-Encoding header is present */
unsigned int allow_chunked_length : 1; /* Allow headers with both
* `Content-Length` and
* `Transfer-Encoding: chunked` set */
unsigned int lenient_http_headers : 1;
uint32_t nread; /* # bytes read in various scenarios */
uint64_t content_length; /* # bytes in body. `(uint64_t) -1` (all bits one)
* if no Content-Length header.
*/
/** READ-ONLY **/
unsigned short http_major;
unsigned short http_minor;
unsigned int status_code : 16; /* responses only */
unsigned int method : 8; /* requests only */
unsigned int http_errno : 7;
/* 1 = Upgrade header was present and the parser has exited because of that.
* 0 = No upgrade header present.
* Should be checked when http_parser_execute() returns in addition to
* error checking.
*/
unsigned int upgrade : 1;
/** PUBLIC **/
void *data; /* A pointer to get hook to the "connection" or "socket" object */
};
struct http_parser_settings {
http_cb on_message_begin;
http_data_cb on_url;
http_data_cb on_status;
http_data_cb on_header_field;
http_data_cb on_header_value;
http_cb on_headers_complete;
http_data_cb on_body;
http_cb on_message_complete;
/* When on_chunk_header is called, the current chunk length is stored
* in parser->content_length.
*/
http_cb on_chunk_header;
http_cb on_chunk_complete;
};
enum http_parser_url_fields
{ UF_SCHEMA = 0
, UF_HOST = 1
, UF_PORT = 2
, UF_PATH = 3
, UF_QUERY = 4
, UF_FRAGMENT = 5
, UF_USERINFO = 6
, UF_MAX = 7
};
/* Result structure for http_parser_parse_url().
*
* Callers should index into field_data[] with UF_* values iff field_set
* has the relevant (1 << UF_*) bit set. As a courtesy to clients (and
* because we probably have padding left over), we convert any port to
* a uint16_t.
*/
struct http_parser_url {
uint16_t field_set; /* Bitmask of (1 << UF_*) values */
uint16_t port; /* Converted UF_PORT string */
struct {
uint16_t off; /* Offset into buffer in which field starts */
uint16_t len; /* Length of run in buffer */
} field_data[UF_MAX];
};
/* Returns the library version. Bits 16-23 contain the major version number,
* bits 8-15 the minor version number and bits 0-7 the patch level.
* Usage example:
*
* unsigned long version = http_parser_version();
* unsigned major = (version >> 16) & 255;
* unsigned minor = (version >> 8) & 255;
* unsigned patch = version & 255;
* printf("http_parser v%u.%u.%u\n", major, minor, patch);
*/
unsigned long http_parser_version(void);
void http_parser_init(http_parser *parser, enum http_parser_type type);
/* Initialize http_parser_settings members to 0
*/
void http_parser_settings_init(http_parser_settings *settings);
/* Executes the parser. Returns number of parsed bytes. Sets
* `parser->http_errno` on error. */
size_t http_parser_execute(http_parser *parser,
const http_parser_settings *settings,
const char *data,
size_t len);
/* If http_should_keep_alive() in the on_headers_complete or
* on_message_complete callback returns 0, then this should be
* the last message on the connection.
* If you are the server, respond with the "Connection: close" header.
* If you are the client, close the connection.
*/
int http_should_keep_alive(const http_parser *parser);
/* Returns a string version of the HTTP method. */
const char *http_method_str(enum http_method m);
/* Returns a string version of the HTTP status code. */
const char *http_status_str(enum http_status s);
/* Return a string name of the given error */
const char *http_errno_name(enum http_errno err);
/* Return a string description of the given error */
const char *http_errno_description(enum http_errno err);
/* Initialize all http_parser_url members to 0 */
void http_parser_url_init(struct http_parser_url *u);
/* Parse a URL; return nonzero on failure */
int http_parser_parse_url(const char *buf, size_t buflen,
int is_connect,
struct http_parser_url *u);
/* Pause or un-pause the parser; a nonzero value pauses */
void http_parser_pause(http_parser *parser, int paused);
/* Checks if this is the final chunk of the body. */
int http_body_is_final(const http_parser *parser);
/* Change the maximum header size provided at compile time. */
void http_parser_set_max_header_size(uint32_t size);
#ifdef __cplusplus
}
#endif
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,919 @@
/*
* coreHTTP v2.1.0
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* @file core_http_client.h
* @brief User facing functions of the HTTP Client library.
*/
#ifndef CORE_HTTP_CLIENT_H_
#define CORE_HTTP_CLIENT_H_
#include <stdint.h>
#include <stddef.h>
/* *INDENT-OFF* */
#ifdef __cplusplus
extern "C" {
#endif
/* *INDENT-ON* */
/* HTTP_DO_NOT_USE_CUSTOM_CONFIG allows building the HTTP Client library
* without a config file. If a config file is provided, the
* HTTP_DO_NOT_USE_CUSTOM_CONFIG macro must not be defined.
*/
#ifndef HTTP_DO_NOT_USE_CUSTOM_CONFIG
#include "core_http_config.h"
#endif
/* Include config defaults header to get default values of configurations not
* defined in core_http_config.h file. */
#include "core_http_config_defaults.h"
/* Transport interface include. */
#include "transport_interface.h"
/* Convenience macros for some HTTP request methods. */
/** @addtogroup http_constants
* @{
*/
#define HTTP_METHOD_GET "GET" /**< HTTP Method GET string. */
#define HTTP_METHOD_PUT "PUT" /**< HTTP Method PUT string. */
#define HTTP_METHOD_POST "POST" /**< HTTP Method POST string. */
#define HTTP_METHOD_HEAD "HEAD" /**< HTTP Method HEAD string. */
/** @}*/
/**
* @ingroup http_constants
* @brief The maximum Content-Length header field and value that could be
* written to the request header buffer.
*/
#define HTTP_MAX_CONTENT_LENGTH_HEADER_LENGTH sizeof( "Content-Length: 4294967295" ) - 1U
/**
* @defgroup http_send_flags HTTPClient_Send Flags
* @brief Values for #HTTPClient_Send sendFlags parameter.
* These flags control some behavior of sending the request or receiving the
* response.
*
* Flags should be bitwise-ORed with each other to change the behavior of
* #HTTPClient_Send.
*/
/**
* @ingroup http_send_flags
* @brief Set this flag to disable automatically writing the Content-Length
* header to send to the server.
*
* This flag is valid only for #HTTPClient_Send sendFlags parameter.
*/
#define HTTP_SEND_DISABLE_CONTENT_LENGTH_FLAG 0x1U
/**
* @defgroup http_request_flags HTTPRequestInfo_t Flags
* @brief Flags for #HTTPRequestInfo_t.reqFlags.
* These flags control what headers are written or not to the
* #HTTPRequestHeaders_t.pBuffer by #HTTPClient_InitializeRequestHeaders.
*
* Flags should be bitwise-ORed with each other to change the behavior of
* #HTTPClient_InitializeRequestHeaders.
*/
/**
* @ingroup http_request_flags
* @brief Set this flag to indicate that the request is for a persistent
* connection.
*
* Setting this will cause a "Connection: Keep-Alive" to be written to the
* request headers.
*
* This flag is valid only for #HTTPRequestInfo_t reqFlags parameter.
*/
#define HTTP_REQUEST_KEEP_ALIVE_FLAG 0x1U
/**
* @defgroup http_response_flags HTTPResponse_t Flags
* @brief Flags for #HTTPResponse_t.respFlags.
* These flags are populated in #HTTPResponse_t.respFlags by the #HTTPClient_Send
* function.
*
* A flag's value can be extracted from #HTTPResponse_t.respFlags with a
* bitwise-AND.
*/
/**
* @ingroup http_response_flags
* @brief This will be set to true if header "Connection: close" is found.
*
* If a "Connection: close" header is present the application should always
* close the connection.
*
* This flag is valid only for #HTTPResponse_t.respFlags.
*/
#define HTTP_RESPONSE_CONNECTION_CLOSE_FLAG 0x1U
/**
* @ingroup http_response_flags
* @brief This will be set to true if header "Connection: Keep-Alive" is found.
*
* This flag is valid only for #HTTPResponse_t.respFlags.
*/
#define HTTP_RESPONSE_CONNECTION_KEEP_ALIVE_FLAG 0x2U
/**
* @ingroup http_constants
* @brief Flag that represents End of File byte in the range specification of
* a Range Request.
* This flag should be used ONLY for 2 kinds of range specifications when
* creating the Range Request header through the #HTTPClient_AddRangeHeader
* function:
* - When the requested range is all bytes from the starting range byte to
* the end of file.
* - When the requested range is for the last N bytes of the file.
* In both cases, this value should be used for the "rangeEnd" parameter.
*/
#define HTTP_RANGE_REQUEST_END_OF_FILE -1
/**
* @ingroup http_enum_types
* @brief The HTTP Client library return status.
*/
typedef enum HTTPStatus
{
/**
* @brief The HTTP Client library function completed successfully.
*
* Functions that may return this value:
* - #HTTPClient_InitializeRequestHeaders
* - #HTTPClient_AddHeader
* - #HTTPClient_AddRangeHeader
* - #HTTPClient_Send
* - #HTTPClient_ReadHeader
*/
HTTPSuccess,
/**
* @brief The HTTP Client library function input an invalid parameter.
*
* Functions that may return this value:
* - #HTTPClient_InitializeRequestHeaders
* - #HTTPClient_AddHeader
* - #HTTPClient_AddRangeHeader
* - #HTTPClient_Send
* - #HTTPClient_ReadHeader
*/
HTTPInvalidParameter,
/**
* @brief A network error was returned from the transport interface.
*
* Functions that may return this value:
* - #HTTPClient_Send
*/
HTTPNetworkError,
/**
* @brief Part of the HTTP response was received from the network.
*
* Functions that may return this value:
* - #HTTPClient_Send
*/
HTTPPartialResponse,
/**
* @brief No HTTP response was received from the network.
*
* This can occur only if there was no data received from the transport
* interface.
*
* Functions that may return this value:
* - #HTTPClient_Send
*/
HTTPNoResponse,
/**
* @brief The application buffer was not large enough for the HTTP request
* headers or the HTTP response message.
*
* Functions that may return this value:
* - #HTTPClient_InitializeRequestHeaders
* - #HTTPClient_AddHeader
* - #HTTPClient_AddRangeHeader
* - #HTTPClient_Send
*/
HTTPInsufficientMemory,
/**
* @brief The server sent more headers than the configured
* #HTTP_MAX_RESPONSE_HEADERS_SIZE_BYTES.
*
* Functions that may return this value:
* - #HTTPClient_Send
*/
HTTPSecurityAlertResponseHeadersSizeLimitExceeded,
/**
* @brief A response contained the "Connection: close" header, but there
* was more data at the end of the complete message.
*
* Functions that may return this value:
* - #HTTPClient_Send
*/
HTTPSecurityAlertExtraneousResponseData,
/**
* @brief The server sent a chunk header containing an invalid character.
*
* Functions that may return this value:
* - #HTTPClient_Send
*/
HTTPSecurityAlertInvalidChunkHeader,
/**
* @brief The server sent a response with an invalid character in the
* HTTP protocol version.
*
* Functions that may return this value:
* - #HTTPClient_Send
*/
HTTPSecurityAlertInvalidProtocolVersion,
/**
* @brief The server sent a response with an invalid character in the
* HTTP status-code or the HTTP status code is out of range.
*
* Functions that may return this value:
* - #HTTPClient_Send
*/
HTTPSecurityAlertInvalidStatusCode,
/**
* @brief An invalid character was found in the HTTP response message or in
* the HTTP request header.
*
* Functions that may return this value:
* - #HTTPClient_AddHeader
* - #HTTPClient_Send
*/
HTTPSecurityAlertInvalidCharacter,
/**
* @brief The response contains either an invalid character in the
* Content-Length header or a Content-Length header when it was not expected
* to be present.
*
* Functions that may return this value:
* - #HTTPClient_Send
*/
HTTPSecurityAlertInvalidContentLength,
/**
* @brief An error occurred in the third-party parsing library.
*
* Functions that may return this value:
* - #HTTPClient_Send
* - #HTTPClient_ReadHeader
*/
HTTPParserInternalError,
/**
* @brief The requested header field was not found in the response buffer.
*
* Functions that may return this value:
* - #HTTPClient_ReadHeader
*/
HTTPHeaderNotFound,
/**
* @brief The HTTP response, provided for parsing, is either corrupt or
* incomplete.
*
* Functions that may return this value:
* - #HTTPClient_ReadHeader
*/
HTTPInvalidResponse
} HTTPStatus_t;
/**
* @ingroup http_struct_types
* @brief Represents header data that will be sent in an HTTP request.
*
* The memory for the header data buffer is supplied by the user. Information in
* the buffer will be filled by calling #HTTPClient_InitializeRequestHeaders and
* #HTTPClient_AddHeader. This buffer may be automatically filled with the
* Content-Length header in #HTTPClient_Send, please see
* HTTP_MAX_CONTENT_LENGTH_HEADER_LENGTH for the maximum amount of space needed
* to accommodate the Content-Length header.
*/
typedef struct HTTPRequestHeaders
{
/**
* @brief Buffer to hold the raw HTTP request headers.
*
* This buffer is supplied by the application.
*
* This buffer is owned by the library during #HTTPClient_AddHeader,
* #HTTPClient_AddRangeHeader, #HTTPClient_InitializeRequestHeaders, and
* #HTTPClient_Send. This buffer should not be modified until
* after these functions return.
*
* For optimization this buffer may be re-used with the response. The user
* can re-use this buffer for the storing the response from the server in
* #HTTPResponse_t.pBuffer.
*/
uint8_t * pBuffer;
size_t bufferLen; /**< The length of pBuffer in bytes. */
/**
* @brief The actual size in bytes of headers in the buffer. This field
* is updated by the HTTP Client library functions #HTTPClient_AddHeader,
* and #HTTPClient_InitializeRequestHeaders.
*/
size_t headersLen;
} HTTPRequestHeaders_t;
/**
* @ingroup http_struct_types
* @brief Configurations of the initial request headers.
*/
typedef struct HTTPRequestInfo
{
/**
* @brief The HTTP request method e.g. "GET", "POST", "PUT", or "HEAD".
*/
const char * pMethod;
size_t methodLen; /**< The length of the method in bytes. */
/**
* @brief The Request-URI to the objects of interest, e.g. "/path/to/item.txt".
*/
const char * pPath;
size_t pathLen; /**< The length of the path in bytes. */
/**
* @brief The server's host name, e.g. "my-storage.my-cloud.com".
*
* The host does not have a "https://" or "http://" prepending.
*/
const char * pHost;
size_t hostLen; /**< The length of the host in bytes. */
/**
* @brief Flags to activate other request header configurations.
*
* Please see @ref http_request_flags for more information.
*/
uint32_t reqFlags;
} HTTPRequestInfo_t;
/**
* @ingroup http_struct_types
* @brief Callback to intercept headers during the first parse through of the
* response as it is received from the network.
*/
typedef struct HTTPClient_ResponseHeaderParsingCallback
{
/**
* @brief Invoked when both a header field and its associated header value are found.
* @param[in] pContext User context.
* @param[in] fieldLoc Location of the header field name in the response buffer.
* @param[in] fieldLen Length in bytes of the field name.
* @param[in] valueLoc Location of the header value in the response buffer.
* @param[in] valueLen Length in bytes of the value.
* @param[in] statusCode The HTTP response status-code.
*/
void ( * onHeaderCallback )( void * pContext,
const char * fieldLoc,
size_t fieldLen,
const char * valueLoc,
size_t valueLen,
uint16_t statusCode );
/**
* @brief Private context for the application.
*/
void * pContext;
} HTTPClient_ResponseHeaderParsingCallback_t;
/**
* @ingroup http_callback_types
* @brief Application provided function to query the current time in
* milliseconds.
*
* @return The current time in milliseconds.
*/
typedef uint32_t (* HTTPClient_GetCurrentTimeFunc_t )( void );
/**
* @ingroup http_struct_types
* @brief Represents an HTTP response.
*/
typedef struct HTTPResponse
{
/**
* @brief Buffer for both the raw HTTP header and body.
*
* This buffer is supplied by the application.
*
* This buffer is owned by the library during #HTTPClient_Send and
* #HTTPClient_ReadHeader. This buffer should not be modified until after
* these functions return.
*
* For optimization this buffer may be used with the request headers. The
* request header buffer is configured in #HTTPRequestHeaders_t.pBuffer.
* When the same buffer is used for the request headers, #HTTPClient_Send
* will send the headers in the buffer first, then fill the buffer with
* the response message.
*/
uint8_t * pBuffer;
size_t bufferLen; /**< The length of the response buffer in bytes. */
/**
* @brief Optional callback for intercepting the header during the first
* parse through of the response as is it receive from the network.
* Set to NULL to disable.
*/
HTTPClient_ResponseHeaderParsingCallback_t * pHeaderParsingCallback;
/**
* @brief Optional callback for getting the system time.
*
* This is used to calculate the elapsed time when retrying network reads or
* sends that return zero bytes received or sent, respectively. If this
* field is set to NULL, then network send and receive won't be retried
* after a zero is returned.
*
* If this function is set, then the maximum time for retrying network reads
* that return zero bytes can be set through #HTTP_RECV_RETRY_TIMEOUT_MS.
*
* If this function is set, then the maximum elapsed time between network
* sends greater than zero is set in HTTP_SEND_RETRY_TIMEOUT_MS.
*/
HTTPClient_GetCurrentTimeFunc_t getTime;
/**
* @brief The starting location of the response headers in pBuffer.
*
* This is updated by #HTTPClient_Send.
*/
const uint8_t * pHeaders;
/**
* @brief Byte length of the response headers in pBuffer.
*
* This is updated by #HTTPClient_Send.
*/
size_t headersLen;
/**
* @brief The starting location of the response body in pBuffer.
*
* This is updated by #HTTPClient_Send.
*/
const uint8_t * pBody;
/**
* @brief Byte length of the body in pBuffer.
*
* This is updated by #HTTPClient_Send.
*/
size_t bodyLen;
/* Useful HTTP header values found. */
/**
* @brief The HTTP response Status-Code.
*
* This is updated by #HTTPClient_Send.
*/
uint16_t statusCode;
/**
* @brief The value in the "Content-Length" header is returned here.
*
* This is updated by #HTTPClient_Send.
*/
size_t contentLength;
/**
* @brief Count of the headers sent by the server.
*
* This is updated by #HTTPClient_Send.
*/
size_t headerCount;
/**
* @brief Flags of useful headers found in the response.
*
* This is updated by #HTTPClient_Send. Please see @ref http_response_flags
* for more information.
*/
uint32_t respFlags;
int8_t chunked;
int8_t eof;
int8_t has_begin;
uint8_t* chunked_buf;
uint16_t chunked_len;
int8_t eof_time;
} HTTPResponse_t;
/**
* @brief Initialize the request headers, stored in
* #HTTPRequestHeaders_t.pBuffer, with initial configurations from
* #HTTPRequestInfo_t. This method is expected to be called before sending a
* new request.
*
* Upon return, #HTTPRequestHeaders_t.headersLen will be updated with the number
* of bytes written.
*
* Each line in the header is listed below and written in this order:
* <#HTTPRequestInfo_t.pMethod> <#HTTPRequestInfo_t.pPath> <#HTTP_PROTOCOL_VERSION>
* User-Agent: <#HTTP_USER_AGENT_VALUE>
* Host: <#HTTPRequestInfo_t.pHost>
*
* Note that "Connection" header can be added and set to "keep-alive" by
* activating the HTTP_REQUEST_KEEP_ALIVE_FLAG in #HTTPRequestInfo_t.reqFlags.
*
* @param[in] pRequestHeaders Request header buffer information.
* @param[in] pRequestInfo Initial request header configurations.
* @return One of the following:
* - #HTTPSuccess (If successful)
* - #HTTPInvalidParameter (If any provided parameters or their members are invalid.)
* - #HTTPInsufficientMemory (If provided buffer size is not large enough to hold headers.)
*
* **Example**
* @code{c}
* HTTPStatus_t httpLibraryStatus = HTTPSuccess;
* // Declare an HTTPRequestHeaders_t and HTTPRequestInfo_t.
* HTTPRequestHeaders_t requestHeaders = { 0 };
* HTTPRequestInfo_t requestInfo = { 0 };
* // A buffer that will fit the Request-Line, the User-Agent header line, and
* // the Host header line.
* uint8_t requestHeaderBuffer[ 256 ] = { 0 };
*
* // Set a buffer to serialize request headers to.
* requestHeaders.pBuffer = requestHeaderBuffer;
* requestHeaders.bufferLen = 256;
*
* // Set the Method, Path, and Host in the HTTPRequestInfo_t.
* requestInfo.pMethod = HTTP_METHOD_GET;
* requestInfo.methodLen = sizeof( HTTP_METHOD_GET ) - 1U;
* requestInfo.pPath = "/html/rfc2616"
* requestInfo.pathLen = sizeof( "/html/rfc2616" ) - 1U;
* requestInfo.pHost = "tools.ietf.org"
* requestInfo.hostLen = sizeof( "tools.ietf.org" ) - 1U;
* requestInfo.reqFlags |= HTTP_REQUEST_KEEP_ALIVE_FLAG;
*
* httpLibraryStatus = HTTPClient_InitializeRequestHeaders( &requestHeaders,
* &requestInfo );
* @endcode
*/
/* @[declare_httpclient_initializerequestheaders] */
HTTPStatus_t HTTPClient_InitializeRequestHeaders( HTTPRequestHeaders_t * pRequestHeaders,
const HTTPRequestInfo_t * pRequestInfo );
/* @[declare_httpclient_initializerequestheaders] */
/**
* @brief Add a header to the request headers stored in
* #HTTPRequestHeaders_t.pBuffer.
*
* Upon return, pRequestHeaders->headersLen will be updated with the number of
* bytes written.
*
* Headers are written in the following format:
*
* @code
* <field>: <value>\r\n\r\n
* @endcode
*
* The trailing `\r\n` that denotes the end of the header lines is overwritten,
* if it already exists in the buffer.
*
* @note This function validates only that `\r`, `\n`, and `:` are not present
* in @p pValue or @p pField. `:` is allowed in @p pValue.
*
* @param[in] pRequestHeaders Request header buffer information.
* @param[in] pField The header field name to write.
* The data should be ISO 8859-1 (Latin-1) encoded per the HTTP standard,
* but the API does not perform the character set validation.
* @param[in] fieldLen The byte length of the header field name.
* @param[in] pValue The header value to write.
* The data should be ISO 8859-1 (Latin-1) encoded per the HTTP standard,
* but the API does not perform the character set validation.
* @param[in] valueLen The byte length of the header field value.
*
* @return One of the following:
* - #HTTPSuccess (If successful.)
* - #HTTPInvalidParameter (If any provided parameters or their members are invalid.)
* - #HTTPInsufficientMemory (If application-provided buffer is not large enough to hold headers.)
* - #HTTPSecurityAlertInvalidCharacter (If an invalid character was found in @p pField or @p pValue.)
*
* **Example**
* @code{c}
* HTTPStatus_t httpLibraryStatus = HTTPSuccess;
* // Assume that requestHeaders has already been initialized with
* // HTTPClient_InitializeRequestHeaders().
* HTTPRequestHeaders_t requestHeaders;
*
* httpLibraryStatus = HTTPClient_AddHeader( &requestHeaders,
* "Request-Header-Field",
* sizeof( "Request-Header-Field" ) - 1U,
* "Request-Header-Value",
* sizeof("Request-Header-Value") - 1U );
* @endcode
*/
/* @[declare_httpclient_addheader] */
HTTPStatus_t HTTPClient_AddHeader( HTTPRequestHeaders_t * pRequestHeaders,
const char * pField,
size_t fieldLen,
const char * pValue,
size_t valueLen );
/* @[declare_httpclient_addheader] */
/**
* @brief Add the byte range request header to the request headers store in
* #HTTPRequestHeaders_t.pBuffer.
*
* For example, if requesting for the first 1kB of a file the following would be
* written: `Range: bytes=0-1023\r\n\r\n`.
*
* The trailing `\r\n` that denotes the end of the header lines is overwritten,
* if it already exists in the buffer.
*
* There are 3 different forms of range specification, determined by the
* combination of @a rangeStartOrLastNBytes and @a rangeEnd parameter values:
*
* 1. Request containing both parameters for the byte range [rangeStart, rangeEnd]
* where @a rangeStartOrLastNBytes <= @a rangeEnd.
* Example request header line: `Range: bytes=0-1023\r\n` for requesting bytes in the range [0, 1023].<br>
* **Example**
* @code{c}
* HTTPStatus_t httpLibraryStatus = HTTPSuccess;
* // Assume that requestHeaders has already been initialized with
* // HTTPClient_InitializeRequestHeaders().
* HTTPRequestHeaders_t requestHeaders;
*
* // Request for bytes 0 to 1023.
* httpLibraryStatus = HTTPClient_AddRangeHeader( &requestHeaders, 0, 1023 );
* @endcode
*
* 2. Request for the last N bytes, represented by @p rangeStartOrlastNbytes.
* @p rangeStartOrlastNbytes should be negative and @p rangeEnd should be
* #HTTP_RANGE_REQUEST_END_OF_FILE.
* Example request header line: `Range: bytes=-512\r\n` for requesting the last 512 bytes
* (or bytes in the range [512, 1023] for a 1KB sized file).<br>
* **Example**
* @code{c}
* HTTPStatus_t httpLibraryStatus = HTTPSuccess;
* // Assume that requestHeaders has already been initialized with
* // HTTPClient_InitializeRequestHeaders().
* HTTPRequestHeaders_t requestHeaders;
*
* // Request for the last 512 bytes.
* httpLibraryStatus = HTTPClient_AddRangeHeader( &requestHeaders, -512, HTTP_RANGE_REQUEST_END_OF_FILE)
* @endcode
*
* 3. Request for all bytes (till the end of byte sequence) from byte N,
* represented by @p rangeStartOrlastNbytes.
* @p rangeStartOrlastNbytes should be >= 0 and @p rangeEnd should be
* #HTTP_RANGE_REQUEST_END_OF_FILE.<br>
* Example request header line: `Range: bytes=256-\r\n` for requesting all bytes after and
* including byte 256 (or bytes in the range [256,1023] for a 1kB sized file).<br>
* **Example**
* @code{c}
* HTTPStatus_t httpLibraryStatus = HTTPSuccess;
* // Assume that requestHeaders has already been initialized with
* // HTTPClient_InitializeRequestHeaders().
* HTTPRequestHeaders_t requestHeaders;
*
* // Request for all bytes from byte 256 onward.
* httpLibraryStatus = HTTPClient_AddRangeHeader( &requestHeaders, 256, HTTP_RANGE_REQUEST_END_OF_FILE)
* @endcode
*
* @param[in] pRequestHeaders Request header buffer information.
* @param[in] rangeStartOrlastNbytes Represents either the starting byte
* for a range OR the last N number of bytes in the requested file.
* @param[in] rangeEnd The ending range for the requested file. For end of file
* byte in Range Specifications 2. and 3., #HTTP_RANGE_REQUEST_END_OF_FILE
* should be passed.
*
* @return Returns the following status codes:
* #HTTPSuccess, if successful.
* #HTTPInvalidParameter, if input parameters are invalid, including when
* the @p rangeStartOrlastNbytes and @p rangeEnd parameter combination is invalid.
* #HTTPInsufficientMemory, if the passed #HTTPRequestHeaders_t.pBuffer
* contains insufficient remaining memory for storing the range request.
*/
/* @[declare_httpclient_addrangeheader] */
HTTPStatus_t HTTPClient_AddRangeHeader( HTTPRequestHeaders_t * pRequestHeaders,
int32_t rangeStartOrlastNbytes,
int32_t rangeEnd );
/* @[declare_httpclient_addrangeheader] */
/**
* @brief Send the request headers in #HTTPRequestHeaders_t.pBuffer and request
* body in @p pRequestBodyBuf over the transport. The response is received in
* #HTTPResponse_t.pBuffer.
*
* If #HTTP_SEND_DISABLE_CONTENT_LENGTH_FLAG is not set in parameter @p sendFlags,
* then the Content-Length to be sent to the server is automatically written to
* @p pRequestHeaders. The Content-Length will not be written when there is
* no request body. If there is not enough room in the buffer to write the
* Content-Length then #HTTPInsufficientMemory is returned. Please see
* #HTTP_MAX_CONTENT_LENGTH_HEADER_LENGTH for the maximum Content-Length header
* field and value that could be written to the buffer.
*
* The application should close the connection with the server if any of the
* following errors are returned:
* - #HTTPSecurityAlertResponseHeadersSizeLimitExceeded
* - #HTTPSecurityAlertExtraneousResponseData
* - #HTTPSecurityAlertInvalidChunkHeader
* - #HTTPSecurityAlertInvalidProtocolVersion
* - #HTTPSecurityAlertInvalidStatusCode
* - #HTTPSecurityAlertInvalidCharacter
* - #HTTPSecurityAlertInvalidContentLength
*
* The @p pResponse returned is valid only if this function returns HTTPSuccess.
*
* @param[in] pTransport Transport interface, see #TransportInterface_t for
* more information.
* @param[in] pRequestHeaders Request configuration containing the buffer of
* headers to send.
* @param[in] pRequestBodyBuf Optional Request entity body. Set to NULL if there
* is no request body.
* @param[in] reqBodyBufLen The length of the request entity in bytes.
* @param[in] pResponse The response message and some notable response
* parameters will be returned here on success.
* @param[in] sendFlags Flags which modify the behavior of this function. Please
* see @ref http_send_flags for more information.
*
* @return One of the following:
* - #HTTPSuccess (If successful.)
* - #HTTPInvalidParameter (If any provided parameters or their members are invalid.)
* - #HTTPNetworkError (Errors in sending or receiving over the transport interface.)
* - #HTTPPartialResponse (Part of an HTTP response was received in a partially filled response buffer.)
* - #HTTPNoResponse (No data was received from the transport interface.)
* - #HTTPInsufficientMemory (The response received could not fit into the response buffer
* or extra headers could not be sent in the request.)
* - #HTTPParserInternalError (Internal parsing error.)\n\n
* Security alerts are listed below, please see #HTTPStatus_t for more information:
* - #HTTPSecurityAlertResponseHeadersSizeLimitExceeded
* - #HTTPSecurityAlertExtraneousResponseData
* - #HTTPSecurityAlertInvalidChunkHeader
* - #HTTPSecurityAlertInvalidProtocolVersion
* - #HTTPSecurityAlertInvalidStatusCode
* - #HTTPSecurityAlertInvalidCharacter
* - #HTTPSecurityAlertInvalidContentLength
*
* **Example**
* @code{c}
* // Variables used in this example.
* HTTPStatus_t httpLibraryStatus = HTTPSuccess;
* TransportInterface_t transportInterface = { 0 };
* HTTPResponse_t = { 0 };
* char requestBody[] = "This is an example request body.";
*
* // Assume that requestHeaders has been initialized with
* // HTTPClient_InitializeResponseHeaders() and any additional headers have
* // been added with HTTPClient_AddHeader().
* HTTPRequestHeaders_t requestHeaders;
*
* // Set the transport interface with platform specific functions that are
* // assumed to be implemented elsewhere.
* transportInterface.recv = myPlatformTransportReceive;
* transportInterface.send = myPlatformTransportSend;
* transportInterface.pNetworkContext = myPlatformNetworkContext;
*
* // Set the buffer to receive the HTTP response message into. The buffer is
* // dynamically allocated for demonstration purposes only.
* response.pBuffer = ( uint8_t* )malloc( 1024 );
* response.bufferLen = 1024;
*
* httpLibraryStatus = HTTPClient_Send( &transportInterface,
* &requestHeaders,
* requestBody,
* sizeof( requestBody ) - 1U,
* &response,
* 0 );
*
* if( httpLibraryStatus == HTTPSuccess )
* {
* if( response.status == 200 )
* {
* // Handle a response Status-Code of 200 OK.
* }
* }
* @endcode
*/
/* @[declare_httpclient_send] */
HTTPStatus_t HTTPClient_Send( const TransportInterface_t * pTransport,
HTTPRequestHeaders_t * pRequestHeaders,
const uint8_t * pRequestBodyBuf,
size_t reqBodyBufLen,
HTTPResponse_t * pResponse,
uint32_t sendFlags );
/* @[declare_httpclient_send] */
HTTPStatus_t HTTPClient_Recv(TransportInterface_t *pTransport, HTTPResponse_t *pResponse);
HTTPStatus_t HTTPClient_Seek(
const TransportInterface_t *pTransport, HTTPRequestHeaders_t *pRequestHeaders);
/**
* @brief Read a header from a buffer containing a complete HTTP response.
* This will return the location of the response header value in the
* #HTTPResponse_t.pBuffer buffer.
*
* The location, within #HTTPResponse_t.pBuffer, of the value found, will be
* returned in @p pValue. If the header value is empty for the found @p pField,
* then this function will return #HTTPSuccess, and set the values for
* @p pValueLoc and @p pValueLen as NULL and zero respectively. According to
* RFC 2616, it is not invalid to have an empty value for some header fields.
*
* @note This function should only be called on a complete HTTP response. If the
* request is sent through the #HTTPClient_Send function, the #HTTPResponse_t is
* incomplete until #HTTPClient_Send returns.
*
* @param[in] pResponse The buffer containing the completed HTTP response.
* @param[in] pField The header field name to read.
* @param[in] fieldLen The length of the header field name in bytes.
* @param[out] pValueLoc This will be populated with the location of the
* header value in the response buffer, #HTTPResponse_t.pBuffer.
* @param[out] pValueLen This will be populated with the length of the
* header value in bytes.
*
* @return One of the following:
* - #HTTPSuccess (If successful.)
* - #HTTPInvalidParameter (If any provided parameters or their members are invalid.)
* - #HTTPHeaderNotFound (Header is not found in the passed response buffer.)
* - #HTTPInvalidResponse (Provided response is not a valid HTTP response for parsing.)
* - #HTTPParserInternalError(If an error in the response parser.)
*
* **Example**
* @code{c}
* HTTPStatus_t httpLibraryStatus = HTTPSuccess;
* // Assume that response is returned from a successful invocation of
* // HTTPClient_Send().
* HTTPResponse_t response;
*
* char * pDateLoc = NULL;
* size_t dateLen = 0;
* // Search for a "Date" header field. pDateLoc will be the location of the
* // Date header value in response.pBuffer.
* httpLibraryStatus = HTTPClient_ReadHeader( &response,
* "Date",
* sizeof("Date") - 1,
* &pDateLoc,
* &dateLen );
* @endcode
*/
/* @[declare_httpclient_readheader] */
HTTPStatus_t HTTPClient_ReadHeader( const HTTPResponse_t * pResponse,
const char * pField,
size_t fieldLen,
const char ** pValueLoc,
size_t * pValueLen );
/* @[declare_httpclient_readheader] */
/**
* @brief Error code to string conversion utility for HTTP Client library.
*
* @note This returns constant strings, which should not be modified.
*
* @param[in] status The status code to convert to a string.
*
* @return The string representation of the status code.
*/
/* @[declare_httpclient_strerror] */
const char * HTTPClient_strerror( HTTPStatus_t status );
/* @[declare_httpclient_strerror] */
/* *INDENT-OFF* */
#ifdef __cplusplus
}
#endif
/* *INDENT-ON* */
#endif /* ifndef CORE_HTTP_CLIENT_H_ */

View File

@@ -0,0 +1,282 @@
/*
* coreHTTP v2.1.0
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* @file core_http_client_private.h
* @brief Internal definitions to the HTTP Client library.
*/
#ifndef CORE_HTTP_CLIENT_PRIVATE_H_
#define CORE_HTTP_CLIENT_PRIVATE_H_
/* Third-party http-parser include. */
#include "http_parser.h"
/* *INDENT-OFF* */
#ifdef __cplusplus
extern "C" {
#endif
/* *INDENT-ON* */
/**
* @brief The HTTP protocol version of this library is HTTP/1.1.
*/
#define HTTP_PROTOCOL_VERSION "HTTP/1.1"
#define HTTP_PROTOCOL_VERSION_LEN ( sizeof( HTTP_PROTOCOL_VERSION ) - 1U ) /**< The length of #HTTP_PROTOCOL_VERSION. */
/**
* @brief Default value when pRequestInfo->pPath == NULL.
*/
#define HTTP_EMPTY_PATH "/"
#define HTTP_EMPTY_PATH_LEN ( sizeof( HTTP_EMPTY_PATH ) - 1U ) /**< The length of #HTTP_EMPTY_PATH. */
/* Constants for HTTP header formatting. */
#define HTTP_HEADER_LINE_SEPARATOR "\r\n" /**< HTTP header field lines are separated by `\r\n`. */
#define HTTP_HEADER_LINE_SEPARATOR_LEN ( sizeof( HTTP_HEADER_LINE_SEPARATOR ) - 1U ) /**< The length of #HTTP_HEADER_LINE_SEPARATOR. */
#define HTTP_HEADER_END_INDICATOR "\r\n\r\n" /**< The HTTP header is complete when `\r\n\r\n` is found. */
#define HTTP_HEADER_END_INDICATOR_LEN ( sizeof( HTTP_HEADER_END_INDICATOR ) - 1U ) /**< The length of #HTTP_HEADER_END_INDICATOR. */
#define HTTP_HEADER_FIELD_SEPARATOR ": " /**< HTTP header field and values are separated by ": ". */
#define HTTP_HEADER_FIELD_SEPARATOR_LEN ( sizeof( HTTP_HEADER_FIELD_SEPARATOR ) - 1U ) /**< The length of #HTTP_HEADER_FIELD_SEPARATOR. */
#define SPACE_CHARACTER ' ' /**< A space character macro to help with serializing a request. */
#define SPACE_CHARACTER_LEN ( 1U ) /**< The length of #SPACE_CHARACTER. */
#define DASH_CHARACTER '-' /**< A dash character macro to help with serializing a request. */
#define DASH_CHARACTER_LEN ( 1U ) /**< The length of #DASH_CHARACTER. */
/* Constants for HTTP header copy checks. */
#define CARRIAGE_RETURN_CHARACTER '\r' /**< A carriage return character to help with header validation. */
#define LINEFEED_CHARACTER '\n' /**< A linefeed character to help with header validation. */
#define COLON_CHARACTER ':' /**< A colon character to help with header validation. */
/**
* @brief Indicator for function #httpHeaderStrncpy that the pSrc parameter is a
* header value.
*/
#define HTTP_HEADER_STRNCPY_IS_VALUE 0U
/**
* @brief Indicator for function #httpHeaderStrncpy that the pSrc parameter is a
* header field.
*/
#define HTTP_HEADER_STRNCPY_IS_FIELD 1U
/* Constants for header fields added automatically during the request
* initialization. */
#define HTTP_USER_AGENT_FIELD "User-Agent" /**< HTTP header field "User-Agent". */
#define HTTP_USER_AGENT_FIELD_LEN ( sizeof( HTTP_USER_AGENT_FIELD ) - 1U ) /**< The length of #HTTP_USER_AGENT_FIELD. */
#define HTTP_HOST_FIELD "Host" /**< HTTP header field "Host". */
#define HTTP_HOST_FIELD_LEN ( sizeof( HTTP_HOST_FIELD ) - 1U ) /**< The length of #HTTP_HOST_FIELD. */
#define HTTP_USER_AGENT_VALUE_LEN ( sizeof( HTTP_USER_AGENT_VALUE ) - 1U ) /**< The length of #HTTP_USER_AGENT_VALUE. */
/* Constants for header fields added based on flags. */
#define HTTP_CONNECTION_FIELD "Connection" /**< HTTP header field "Connection". */
#define HTTP_CONNECTION_FIELD_LEN ( sizeof( HTTP_CONNECTION_FIELD ) - 1U ) /**< The length of #HTTP_CONNECTION_FIELD. */
#define HTTP_CONTENT_LENGTH_FIELD "Content-Length" /**< HTTP header field "Content-Length". */
#define HTTP_CONTENT_LENGTH_FIELD_LEN ( sizeof( HTTP_CONTENT_LENGTH_FIELD ) - 1U ) /**< The length of #HTTP_CONTENT_LENGTH_FIELD. */
/* Constants for header values added based on flags. */
/* MISRA Rule 5.4 flags the following macro's name as ambiguous from the
* one postfixed with _LEN. This rule is suppressed for naming consistency with
* other HTTP header field and value string and length macros in this file.*/
/* coverity[other_declaration] */
#define HTTP_CONNECTION_KEEP_ALIVE_VALUE "keep-alive" /**< HTTP header value "keep-alive" for the "Connection" header field. */
/* MISRA Rule 5.4 flags the following macro's name as ambiguous from the one
* above it. This rule is suppressed for naming consistency with other HTTP
* header field and value string and length macros in this file.*/
/* coverity[misra_c_2012_rule_5_4_violation] */
#define HTTP_CONNECTION_KEEP_ALIVE_VALUE_LEN ( sizeof( HTTP_CONNECTION_KEEP_ALIVE_VALUE ) - 1U ) /**< The length of #HTTP_CONNECTION_KEEP_ALIVE_VALUE. */
/* Constants relating to Range Requests. */
/* MISRA Rule 5.4 flags the following macro's name as ambiguous from the
* one postfixed with _LEN. This rule is suppressed for naming consistency with
* other HTTP header field and value string and length macros in this file.*/
/* coverity[other_declaration] */
#define HTTP_RANGE_REQUEST_HEADER_FIELD "Range" /**< HTTP header field "Range". */
/* MISRA Rule 5.4 flags the following macro's name as ambiguous from the one
* above it. This rule is suppressed for naming consistency with other HTTP
* header field and value string and length macros in this file.*/
/* coverity[misra_c_2012_rule_5_4_violation] */
#define HTTP_RANGE_REQUEST_HEADER_FIELD_LEN ( sizeof( HTTP_RANGE_REQUEST_HEADER_FIELD ) - 1U ) /**< The length of #HTTP_RANGE_REQUEST_HEADER_FIELD. */
/* MISRA Rule 5.4 flags the following macro's name as ambiguous from the
* one postfixed with _LEN. This rule is suppressed for naming consistency with
* other HTTP header field and value string and length macros in this file.*/
/* coverity[other_declaration] */
#define HTTP_RANGE_REQUEST_HEADER_VALUE_PREFIX "bytes=" /**< HTTP required header value prefix when specifying a byte range for partial content. */
/* MISRA Rule 5.4 flags the following macro's name as ambiguous from the one
* above it. This rule is suppressed for naming consistency with other HTTP
* header field and value string and length macros in this file.*/
/* coverity[misra_c_2012_rule_5_4_violation] */
#define HTTP_RANGE_REQUEST_HEADER_VALUE_PREFIX_LEN ( sizeof( HTTP_RANGE_REQUEST_HEADER_VALUE_PREFIX ) - 1U ) /**< The length of #HTTP_RANGE_REQUEST_HEADER_VALUE_PREFIX. */
/**
* @brief Maximum value of a 32 bit signed integer is 2,147,483,647.
*
* Used for calculating buffer space for ASCII representation of range values.
*/
#define MAX_INT32_NO_OF_DECIMAL_DIGITS 10U
/**
* @brief Maximum buffer space for storing a Range Request Value.
*
* The largest Range Request value is of the form:
* "bytes=<Max-Integer-Value>-<Max-Integer-Value>"
*/
#define HTTP_MAX_RANGE_REQUEST_VALUE_LEN \
( HTTP_RANGE_REQUEST_HEADER_VALUE_PREFIX_LEN + MAX_INT32_NO_OF_DECIMAL_DIGITS + \
1U /* Dash character '-' */ + MAX_INT32_NO_OF_DECIMAL_DIGITS )
/**
* @brief Return value for the http-parser registered callback to signal halting
* further execution.
*/
#define HTTP_PARSER_STOP_PARSING 1
/**
* @brief Return value for http_parser registered callback to signal
* continuation of HTTP response parsing.
*/
#define HTTP_PARSER_CONTINUE_PARSING 0
/**
* @brief The minimum request-line in the headers has a possible one character
* custom method and a single forward / or asterisk * for the path:
*
* @code
* <1 character custom method> <1 character / or *> HTTP/1.x\r\n\r\n
* @endcode
*
* Therefore the minimum length is 16. If this minimum request-line is not
* satisfied, then the request headers to send are invalid.
*
* Note that custom methods are allowed per:
* https://tools.ietf.org/html/rfc2616#section-5.1.1.
*/
#define HTTP_MINIMUM_REQUEST_LINE_LENGTH 16u
/**
* @brief The state of the response message parsed after function
* #parseHttpResponse returns.
*/
typedef enum HTTPParsingState_t
{
HTTP_PARSING_NONE = 0, /**< The parser has not started reading any response. */
HTTP_PARSING_INCOMPLETE, /**< The parser found a partial reponse. */
HTTP_PARSING_COMPLETE /**< The parser found the entire response. */
} HTTPParsingState_t;
/**
* @brief An aggregator that represents the user-provided parameters to the
* #HTTPClient_ReadHeader API function. This will be used as context parameter
* for the parsing callbacks used by the API function.
*/
typedef struct findHeaderContext
{
const char * pField; /**< The field that is being searched for. */
size_t fieldLen; /**< The length of pField. */
const char ** pValueLoc; /**< The location of the value found in the buffer. */
size_t * pValueLen; /**< the length of the value found. */
uint8_t fieldFound; /**< Indicates that the header field was found during parsing. */
uint8_t valueFound; /**< Indicates that the header value was found during parsing. */
} findHeaderContext_t;
/**
* @brief The HTTP response parsing context for a response fresh from the
* server. This context is passed into the http-parser registered callbacks.
* The registered callbacks are private functions of the form
* httpParserXXXXCallbacks().
*
* The transitions of the httpParserXXXXCallback() functions are shown below.
* The XXXX is replaced by the strings in the state boxes:
*
* +---------------------+
* |onMessageBegin |
* +--------+------------+
* |
* |
* |
* v
* +--------+------------+
* |onStatus |
* +--------+------------+
* |
* |
* |
* v
* +--------+------------+
* |onHeaderField +<---+
* +--------+------------+ |
* | |
* | |(More headers)
* | |
* v |
* +--------+------------+ |
* |onHeaderValue +----^
* +--------+------------+
* |
* |
* |
* v
* +--------+------------+
* |onHeadersComplete |
* +---------------------+
* |
* |
* |
* v
* +--------+------------+
* |onBody +<---+
* +--------+--------+---+ |
* | | |(Transfer-encoding chunked body)
* | | |
* | +--------+
* |
* v
* +--------+------------+
* |onMessageComplete |
* +---------------------+
*/
typedef struct HTTPParsingContext
{
http_parser httpParser; /**< Third-party http-parser context. */
HTTPParsingState_t state; /**< The current state of the HTTP response parsed. */
struct HTTPResponse * pResponse; /**< HTTP response associated with this parsing context. */
uint8_t isHeadResponse; /**< HTTP response is for a HEAD request. */
const char * pBufferCur; /**< The current location of the parser in the response buffer. */
const char * pLastHeaderField; /**< Holds the last part of the header field parsed. */
size_t lastHeaderFieldLen; /**< The length of the last header field parsed. */
const char * pLastHeaderValue; /**< Holds the last part of the header value parsed. */
size_t lastHeaderValueLen; /**< The length of the last value field parsed. */
} HTTPParsingContext_t;
/* *INDENT-OFF* */
#ifdef __cplusplus
}
#endif
/* *INDENT-ON* */
#endif /* ifndef CORE_HTTP_CLIENT_PRIVATE_H_ */

View File

@@ -0,0 +1,206 @@
/*
* coreHTTP v2.1.0
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* @file core_http_config_defaults.h
* @brief The default values for the configuration macros for the HTTP Client
* library.
*
* @note This file SHOULD NOT be modified. If custom values are needed for
* any configuration macro, a core_http_config.h file should be provided to
* the HTTP Client library to override the default values defined in this file.
* To use the custom config file, the HTTP_DO_NOT_USE_CUSTOM_CONFIG preprocessor
* macro SHOULD NOT be set.
*/
#ifndef CORE_HTTP_CONFIG_DEFAULTS_
#define CORE_HTTP_CONFIG_DEFAULTS_
/* *INDENT-OFF* */
#ifdef __cplusplus
extern "C" {
#endif
/* *INDENT-ON* */
/**
* @brief Maximum size, in bytes, of headers allowed from the server.
*
* If the total size in bytes of the headers received from the server exceeds
* this configuration, then the status code
* #HTTPSecurityAlertResponseHeadersSizeLimitExceeded is returned from
* #HTTPClient_Send.
*
* <b>Possible values:</b> Any positive 32 bit integer. <br>
* <b>Default value:</b> `2048`
*/
#ifndef HTTP_MAX_RESPONSE_HEADERS_SIZE_BYTES
#define HTTP_MAX_RESPONSE_HEADERS_SIZE_BYTES 2048U
#endif
/**
* @brief The HTTP header "User-Agent" value.
*
* The following header line is automatically written to
* #HTTPRequestHeaders_t.pBuffer:
* "User-Agent: my-platform-name\r\n"
*
* <b>Possible values:</b> Any string. <br>
* <b>Default value:</b> `my-platform-name`
*/
#ifndef HTTP_USER_AGENT_VALUE
#define HTTP_USER_AGENT_VALUE "Mozilla/5.0"
#endif
/**
* @brief The maximum duration between non-empty network reads while receiving
* an HTTP response via the #HTTPClient_Send API function.
*
* The transport receive function may be called multiple times until the end of
* the response is detected by the parser. This timeout represents the maximum
* duration that is allowed without any data reception from the network for the
* incoming response.
*
* If the timeout expires, the #HTTPClient_Send function will return
* #HTTPNetworkError.
*
* If #HTTPResponse_t.getTime is set to NULL, then this HTTP_RECV_RETRY_TIMEOUT_MS
* is unused. When this timeout is unused, #HTTPClient_Send will not retry the
* transport receive calls that return zero bytes read.
*
* <b>Possible values:</b> Any positive 32 bit integer. A small timeout value
* is recommended. <br>
* <b>Default value:</b> `10`
*/
#ifndef HTTP_RECV_RETRY_TIMEOUT_MS
#define HTTP_RECV_RETRY_TIMEOUT_MS ( 10U )
#endif
/**
* @brief The maximum duration between non-empty network transmissions while
* sending an HTTP request via the #HTTPClient_Send API function.
*
* When sending an HTTP request, the transport send function may be called multiple
* times until all of the required number of bytes are sent.
* This timeout represents the maximum duration that is allowed for no data
* transmission over the network through the transport send function.
*
* If the timeout expires, the #HTTPClient_Send function returns #HTTPNetworkError.
*
* If #HTTPResponse_t.getTime is set to NULL, then this HTTP_RECV_RETRY_TIMEOUT_MS
* is unused. When this timeout is unused, #HTTPClient_Send will not retry the
* transport send calls that return zero bytes sent.
*
* <b>Possible values:</b> Any positive 32 bit integer. A small timeout value
* is recommended. <br>
* <b>Default value:</b> `10`
*/
#ifndef HTTP_SEND_RETRY_TIMEOUT_MS
#define HTTP_SEND_RETRY_TIMEOUT_MS ( 10U )
#endif
/**
* @brief Macro that is called in the HTTP Client library for logging "Error" level
* messages.
*
* To enable error level logging in the HTTP Client library, this macro should be mapped to the
* application-specific logging implementation that supports error logging.
*
* @note This logging macro is called in the HTTP Client library with parameters wrapped in
* double parentheses to be ISO C89/C90 standard compliant. For a reference
* POSIX implementation of the logging macros, refer to core_http_config.h files, and the
* logging-stack in demos folder of the
* [AWS IoT Embedded C SDK repository](https://github.com/aws/aws-iot-device-sdk-embedded-C).
*
* <b>Default value</b>: Error logging is turned off, and no code is generated for calls
* to the macro in the HTTP Client library on compilation.
*/
#ifndef LogError
#define LogError( message )
#endif
/**
* @brief Macro that is called in the HTTP Client library for logging "Warning" level
* messages.
*
* To enable warning level logging in the HTTP Client library, this macro should be mapped to the
* application-specific logging implementation that supports warning logging.
*
* @note This logging macro is called in the HTTP Client library with parameters wrapped in
* double parentheses to be ISO C89/C90 standard compliant. For a reference
* POSIX implementation of the logging macros, refer to core_http_config.h files, and the
* logging-stack in demos folder of the
* [AWS IoT Embedded C SDK repository](https://github.com/aws/aws-iot-device-sdk-embedded-C).
*
* <b>Default value</b>: Warning logs are turned off, and no code is generated for calls
* to the macro in the HTTP Client library on compilation.
*/
#ifndef LogWarn
#define LogWarn( message )
#endif
/**
* @brief Macro that is called in the HTTP Client library for logging "Info" level
* messages.
*
* To enable info level logging in the HTTP Client library, this macro should be mapped to the
* application-specific logging implementation that supports info logging.
*
* @note This logging macro is called in the HTTP Client library with parameters wrapped in
* double parentheses to be ISO C89/C90 standard compliant. For a reference
* POSIX implementation of the logging macros, refer to core_http_config.h files, and the
* logging-stack in demos folder of the
* [AWS IoT Embedded C SDK repository](https://github.com/aws/aws-iot-device-sdk-embedded-C).
*
* <b>Default value</b>: Info logging is turned off, and no code is generated for calls
* to the macro in the HTTP Client library on compilation.
*/
#ifndef LogInfo
#define LogInfo( message )
#endif
/**
* @brief Macro that is called in the HTTP Client library for logging "Debug" level
* messages.
*
* To enable debug level logging from HTTP Client library, this macro should be mapped to the
* application-specific logging implementation that supports debug logging.
*
* @note This logging macro is called in the HTTP Client library with parameters wrapped in
* double parentheses to be ISO C89/C90 standard compliant. For a reference
* POSIX implementation of the logging macros, refer to core_http_config.h files, and the
* logging-stack in demos folder of the
* [AWS IoT Embedded C SDK repository](https://github.com/aws/aws-iot-device-sdk-embedded-C).
*
* <b>Default value</b>: Debug logging is turned off, and no code is generated for calls
* to the macro in the HTTP Client library on compilation.
*/
#ifndef LogDebug
#define LogDebug( message )
#endif
/* *INDENT-OFF* */
#ifdef __cplusplus
}
#endif
/* *INDENT-ON* */
#endif /* ifndef CORE_HTTP_CONFIG_DEFAULTS_ */

View File

@@ -0,0 +1,267 @@
/*
* coreHTTP v2.1.0
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* @file transport_interface.h
* @brief Transport interface definitions to send and receive data over the
* network.
*/
#ifndef TRANSPORT_INTERFACE_H_
#define TRANSPORT_INTERFACE_H_
#include <stdint.h>
#include <stddef.h>
#include "http_parser.h"
/* *INDENT-OFF* */
#ifdef __cplusplus
extern "C" {
#endif
/* *INDENT-ON* */
/**
* @transportpage
* @brief The transport interface definition.
*
* @transportsectionoverview
*
* The transport interface is a set of APIs that must be implemented using an
* external transport layer protocol. The transport interface is defined in
* @ref transport_interface.h. This interface allows protocols like MQTT and
* HTTP to send and receive data over the transport layer. This
* interface does not handle connection and disconnection to the server of
* interest. The connection, disconnection, and other transport settings, like
* timeout and TLS setup, must be handled in the user application.
* <br>
*
* The functions that must be implemented are:<br>
* - [Transport Receive](@ref TransportRecv_t)
* - [Transport Send](@ref TransportSend_t)
*
* Each of the functions above take in an opaque context @ref NetworkContext_t.
* The functions above and the context are also grouped together in the
* @ref TransportInterface_t structure:<br><br>
* @snippet this define_transportinterface
* <br>
*
* @transportsectionimplementation
*
* The following steps give guidance on implementing the transport interface:
*
* -# Implementing @ref NetworkContext_t<br><br>
* @snippet this define_networkcontext
* <br>
* @ref NetworkContext_t is the incomplete type <b>struct NetworkContext</b>.
* The implemented struct NetworkContext must contain all of the information
* that is needed to receive and send data with the @ref TransportRecv_t
* and the @ref TransportSend_t implementations.<br>
* In the case of TLS over TCP, struct NetworkContext is typically implemented
* with the TCP socket context and a TLS context.<br><br>
* <b>Example code:</b>
* @code{c}
* struct NetworkContext
* {
* struct MyTCPSocketContext tcpSocketContext;
* struct MyTLSContext tlsContext;
* };
* @endcode
* <br>
* -# Implementing @ref TransportRecv_t<br><br>
* @snippet this define_transportrecv
* <br>
* This function is expected to populate a buffer, with bytes received from the
* transport, and return the number of bytes placed in the buffer.
* In the case of TLS over TCP, @ref TransportRecv_t is typically implemented by
* calling the TLS layer function to receive data. In case of plaintext TCP
* without TLS, it is typically implemented by calling the TCP layer receive
* function. @ref TransportRecv_t may be invoked multiple times by the protocol
* library, if fewer bytes than were requested to receive are returned.
* <br><br>
* <b>Example code:</b>
* @code{c}
* int32_t myNetworkRecvImplementation( NetworkContext_t * pNetworkContext,
* void * pBuffer,
* size_t bytesToRecv )
* {
* int32_t bytesReceived = 0;
* bool callTlsRecvFunc = true;
*
* // For a single byte read request, check if data is available on the network.
* if( bytesToRecv == 1 )
* {
* // If no data is available on the network, do not call TLSRecv
* // to avoid blocking for socket timeout.
* if( TLSRecvCount( pNetworkContext->tlsContext ) == 0 )
* {
* callTlsRecvFunc = false;
* }
* }
*
* if( callTlsRecvFunc == true )
* {
* bytesReceived = TLSRecv( pNetworkContext->tlsContext,
* pBuffer,
* bytesToRecv,
* MY_SOCKET_TIMEOUT );
* if( bytesReceived < 0 )
* {
* // If the error code represents a timeout, then the return
* // code should be translated to zero so that the caller
* // can retry the read operation.
* if( bytesReceived == MY_SOCKET_ERROR_TIMEOUT )
* {
* bytesReceived = 0;
* }
* }
* // Handle other cases.
* }
* return bytesReceived;
* }
* @endcode
* <br>
* -# Implementing @ref TransportSend_t<br><br>
* @snippet this define_transportsend
* <br>
* This function is expected to send the bytes, in the given buffer over the
* transport, and return the number of bytes sent.
* In the case of TLS over TCP, @ref TransportSend_t is typically implemented by
* calling the TLS layer function to send data. In case of plaintext TCP
* without TLS, it is typically implemented by calling the TCP layer send
* function. @ref TransportSend_t may be invoked multiple times by the protocol
* library, if fewer bytes than were requested to send are returned.
* <br><br>
* <b>Example code:</b>
* @code{c}
* int32_t myNetworkSendImplementation( NetworkContext_t * pNetworkContext,
* const void * pBuffer,
* size_t bytesToSend )
* {
* int32_t bytesSent = 0;
* bytesSent = TLSSend( pNetworkContext->tlsContext,
* pBuffer,
* bytesToSend,
* MY_SOCKET_TIMEOUT );
*
* // If underlying TCP buffer is full, set the return value to zero
* // so that caller can retry the send operation.
* if( bytesSent == MY_SOCKET_ERROR_BUFFER_FULL )
* {
* bytesSent = 0;
* }
* else if( bytesSent < 0 )
* {
* // Handle socket error.
* }
* // Handle other cases.
*
* return bytesSent;
* }
* @endcode
*/
/**
* @transportstruct
* @typedef NetworkContext_t
* @brief The NetworkContext is an incomplete type. An implementation of this
* interface must define struct NetworkContext for the system requirements.
* This context is passed into the network interface functions.
*/
/* @[define_networkcontext] */
struct NetworkContext;
typedef struct NetworkContext NetworkContext_t;
/* @[define_networkcontext] */
/**
* @transportcallback
* @brief Transport interface for receiving data on the network.
*
* @note It is RECOMMENDED that the transport receive implementation
* does NOT block when requested to read a single byte. A single byte
* read request can be made by the caller to check whether there is a
* new frame available on the network for reading.
* However, the receive implementation MAY block for a timeout period when
* it is requested to read more than 1 byte. This is because once the caller
* is aware that a new frame is available to read on the network, then
* the likelihood of reading more than one byte over the network becomes high.
*
* @param[in] pNetworkContext Implementation-defined network context.
* @param[in] pBuffer Buffer to receive the data into.
* @param[in] bytesToRecv Number of bytes requested from the network.
*
* @return The number of bytes received or a negative value to indicate
* error.
*
* @note If no data is available on the network to read and no error
* has occurred, zero MUST be the return value. A zero return value
* SHOULD represent that the read operation can be retried by calling
* the API function. Zero MUST NOT be returned if a network disconnection
* has occurred.
*/
/* @[define_transportrecv] */
typedef int32_t ( * TransportRecv_t )( NetworkContext_t * pNetworkContext,
void * pBuffer,
size_t bytesToRecv );
/* @[define_transportrecv] */
/**
* @transportcallback
* @brief Transport interface for sending data over the network.
*
* @param[in] pNetworkContext Implementation-defined network context.
* @param[in] pBuffer Buffer containing the bytes to send over the network stack.
* @param[in] bytesToSend Number of bytes to send over the network.
*
* @return The number of bytes sent or a negative value to indicate error.
*
* @note If no data is transmitted over the network due to a full TX buffer and
* no network error has occurred, this MUST return zero as the return value.
* A zero return value SHOULD represent that the send operation can be retried
* by calling the API function. Zero MUST NOT be returned if a network disconnection
* has occurred.
*/
/* @[define_transportsend] */
typedef int32_t ( * TransportSend_t )( NetworkContext_t * pNetworkContext,
const void * pBuffer,
size_t bytesToSend );
/* @[define_transportsend] */
/**
* @transportstruct
* @brief The transport layer interface.
*/
/* @[define_transportinterface] */
typedef struct TransportInterface
{
TransportRecv_t recv; /**< Transport receive interface. */
TransportSend_t send; /**< Transport send interface. */
NetworkContext_t * pNetworkContext; /**< Implementation-defined network context. */
http_parser httpParser; /**< Third-party http-parser context. */
} TransportInterface_t;
/* @[define_transportinterface] */
/* *INDENT-OFF* */
#ifdef __cplusplus
}
#endif
/* *INDENT-ON* */
#endif /* ifndef TRANSPORT_INTERFACE_H_ */