coreHTTP v2.1.0
HTTP/1.1 Client Library
core_http_client.c File Reference

Implements the user-facing functions in core_http_client.h. More...

#include <assert.h>
#include <string.h>
#include <ctype.h>
#include "core_http_client.h"
#include "core_http_client_private.h"

Functions

static uint32_t getZeroTimestampMs (void)
 When HTTPResponse_t.getTime is set to NULL in HTTPClient_Send then this function will replace that field. More...
 
static HTTPStatus_t sendHttpData (const TransportInterface_t *pTransport, HTTPClient_GetCurrentTimeFunc_t getTimestampMs, const uint8_t *pData, size_t dataLen)
 Send HTTP bytes over the transport send interface. More...
 
static HTTPStatus_t sendHttpHeaders (const TransportInterface_t *pTransport, HTTPClient_GetCurrentTimeFunc_t getTimestampMs, HTTPRequestHeaders_t *pRequestHeaders, size_t reqBodyLen, uint32_t sendFlags)
 Send the HTTP headers over the transport send interface. More...
 
static HTTPStatus_t addContentLengthHeader (HTTPRequestHeaders_t *pRequestHeaders, size_t contentLength)
 Adds the Content-Length header field and value to the pRequestHeaders. More...
 
static HTTPStatus_t sendHttpBody (const TransportInterface_t *pTransport, HTTPClient_GetCurrentTimeFunc_t getTimestampMs, const uint8_t *pRequestBodyBuf, size_t reqBodyBufLen)
 Send the HTTP body over the transport send interface. More...
 
static char * httpHeaderStrncpy (char *pDest, const char *pSrc, size_t len, uint8_t isField)
 A strncpy replacement with HTTP header validation. More...
 
static HTTPStatus_t addHeader (HTTPRequestHeaders_t *pRequestHeaders, const char *pField, size_t fieldLen, const char *pValue, size_t valueLen)
 Write header based on parameters. This method also adds a trailing "\r\n". If a trailing "\r\n" already exists in the HTTP header, this method backtracks in order to write over it and updates the length accordingly. More...
 
static HTTPStatus_t addRangeHeader (HTTPRequestHeaders_t *pRequestHeaders, int32_t rangeStartOrlastNbytes, int32_t rangeEnd)
 Add the byte range request header to the request headers store in HTTPRequestHeaders_t.pBuffer once all the parameters are validated. More...
 
static HTTPStatus_t getFinalResponseStatus (HTTPParsingState_t parsingState, size_t totalReceived, size_t responseBufferLen)
 Get the status of the HTTP response given the parsing state and how much data is in the response buffer. More...
 
static HTTPStatus_t receiveAndParseHttpResponse (const TransportInterface_t *pTransport, HTTPResponse_t *pResponse, const HTTPRequestHeaders_t *pRequestHeaders)
 Receive the HTTP response from the network and parse it. More...
 
static HTTPStatus_t sendHttpRequest (const TransportInterface_t *pTransport, HTTPClient_GetCurrentTimeFunc_t getTimestampMs, HTTPRequestHeaders_t *pRequestHeaders, const uint8_t *pRequestBodyBuf, size_t reqBodyBufLen, uint32_t sendFlags)
 Send the HTTP request over the network. More...
 
static uint8_t convertInt32ToAscii (int32_t value, char *pBuffer, size_t bufferLength)
 Converts an integer value to its ASCII representation in the passed buffer. More...
 
static HTTPStatus_t writeRequestLine (HTTPRequestHeaders_t *pRequestHeaders, const char *pMethod, size_t methodLen, const char *pPath, size_t pathLen)
 This method writes the request line (first line) of the HTTP Header into HTTPRequestHeaders_t.pBuffer and updates length accordingly. More...
 
static HTTPStatus_t findHeaderInResponse (const uint8_t *pBuffer, size_t bufferLen, const char *pField, size_t fieldLen, const char **pValueLoc, size_t *pValueLen)
 Find the specified header field in the response buffer. More...
 
static int findHeaderFieldParserCallback (http_parser *pHttpParser, const char *pFieldLoc, size_t fieldLen)
 The "on_header_field" callback for the HTTP parser used by the findHeaderInResponse function. The callback checks whether the parser header field matched the header being searched for, and sets a flag to represent reception of the header accordingly. More...
 
static int findHeaderValueParserCallback (http_parser *pHttpParser, const char *pValueLoc, size_t valueLen)
 The "on_header_value" callback for the HTTP parser used by the findHeaderInResponse function. The callback sets the user-provided output parameters for header value if the requested header's field was found in the findHeaderFieldParserCallback function. More...
 
static int findHeaderOnHeaderCompleteCallback (http_parser *pHttpParser)
 The "on_header_complete" callback for the HTTP parser used by the findHeaderInResponse function. More...
 
static void initializeParsingContextForFirstResponse (HTTPParsingContext_t *pParsingContext, const HTTPRequestHeaders_t *pRequestHeaders)
 Initialize the parsing context for parsing a response fresh from the server. More...
 
static HTTPStatus_t parseHttpResponse (HTTPParsingContext_t *pParsingContext, HTTPResponse_t *pResponse, size_t parseLen)
 Parses the response buffer in pResponse. More...
 
static int httpParserOnMessageBeginCallback (http_parser *pHttpParser)
 Callback invoked during http_parser_execute() to indicate the start of the HTTP response message. More...
 
static int httpParserOnStatusCallback (http_parser *pHttpParser, const char *pLoc, size_t length)
 Callback invoked during http_parser_execute() when the HTTP response status-code and its associated reason-phrase are found. More...
 
static int httpParserOnHeaderFieldCallback (http_parser *pHttpParser, const char *pLoc, size_t length)
 Callback invoked during http_parser_execute() when an HTTP response header field is found. More...
 
static int httpParserOnHeaderValueCallback (http_parser *pHttpParser, const char *pLoc, size_t length)
 Callback invoked during http_parser_execute() when an HTTP response header value is found. More...
 
static int httpParserOnHeadersCompleteCallback (http_parser *pHttpParser)
 Callback invoked during http_parser_execute() when the end of the headers are found. More...
 
static int httpParserOnBodyCallback (http_parser *pHttpParser, const char *pLoc, size_t length)
 Callback invoked during http_parser_execute() when the HTTP response body is found. More...
 
static int httpParserOnMessageCompleteCallback (http_parser *pHttpParser)
 Callback invoked during http_parser_execute() to indicate the the completion of an HTTP response message. More...
 
static void processCompleteHeader (HTTPParsingContext_t *pParsingContext)
 When a complete header is found the HTTP response header count increases and the application is notified. More...
 
static HTTPStatus_t processHttpParserError (const http_parser *pHttpParser)
 When parsing is complete an error could be indicated in pHttpParser->http_errno. This function translates that error into a library specific error code. More...
 
static int8_t caseInsensitiveStringCmp (const char *str1, const char *str2, size_t n)
 Compares at most the first n bytes of str1 and str2 without case sensitivity and n must be less than the actual size of either string. More...
 
HTTPStatus_t HTTPClient_InitializeRequestHeaders (HTTPRequestHeaders_t *pRequestHeaders, const HTTPRequestInfo_t *pRequestInfo)
 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. More...
 
HTTPStatus_t HTTPClient_AddHeader (HTTPRequestHeaders_t *pRequestHeaders, const char *pField, size_t fieldLen, const char *pValue, size_t valueLen)
 Add a header to the request headers stored in HTTPRequestHeaders_t.pBuffer. More...
 
HTTPStatus_t HTTPClient_AddRangeHeader (HTTPRequestHeaders_t *pRequestHeaders, int32_t rangeStartOrlastNbytes, int32_t rangeEnd)
 Add the byte range request header to the request headers store in HTTPRequestHeaders_t.pBuffer. More...
 
HTTPStatus_t HTTPClient_Send (const TransportInterface_t *pTransport, HTTPRequestHeaders_t *pRequestHeaders, const uint8_t *pRequestBodyBuf, size_t reqBodyBufLen, HTTPResponse_t *pResponse, uint32_t sendFlags)
 Send the request headers in HTTPRequestHeaders_t.pBuffer and request body in pRequestBodyBuf over the transport. The response is received in HTTPResponse_t.pBuffer. More...
 
HTTPStatus_t HTTPClient_ReadHeader (const HTTPResponse_t *pResponse, const char *pField, size_t fieldLen, const char **pValueLoc, size_t *pValueLen)
 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. More...
 
const char * HTTPClient_strerror (HTTPStatus_t status)
 Error code to string conversion utility for HTTP Client library. More...
 

Detailed Description

Implements the user-facing functions in core_http_client.h.

Function Documentation

◆ getZeroTimestampMs()

static uint32_t getZeroTimestampMs ( void  )
static

When HTTPResponse_t.getTime is set to NULL in HTTPClient_Send then this function will replace that field.

Returns
This function always returns zero.

◆ sendHttpData()

static HTTPStatus_t sendHttpData ( const TransportInterface_t pTransport,
HTTPClient_GetCurrentTimeFunc_t  getTimestampMs,
const uint8_t *  pData,
size_t  dataLen 
)
static

Send HTTP bytes over the transport send interface.

Parameters
[in]pTransportTransport interface.
[in]getTimestampMsFunction to retrieve a timestamp in milliseconds.
[in]pDataHTTP request data to send.
[in]dataLenHTTP request data length.
Returns
HTTPSuccess if successful. If there was a network error or less bytes than what were specified were sent, then HTTPNetworkError is returned.

◆ sendHttpHeaders()

static HTTPStatus_t sendHttpHeaders ( const TransportInterface_t pTransport,
HTTPClient_GetCurrentTimeFunc_t  getTimestampMs,
HTTPRequestHeaders_t pRequestHeaders,
size_t  reqBodyLen,
uint32_t  sendFlags 
)
static

Send the HTTP headers over the transport send interface.

Parameters
[in]pTransportTransport interface.
[in]getTimestampMsFunction to retrieve a timestamp in milliseconds.
[in]pRequestHeadersRequest headers to send, it includes the buffer and length.
[in]reqBodyLenThe length of the request body to be sent. This is used to generated a Content-Length header.
[in]sendFlagsApplication provided flags to HTTPClient_Send.
Returns
HTTPSuccess if successful. If there was a network error or less bytes than what were specified were sent, then HTTPNetworkError is returned.

◆ addContentLengthHeader()

static HTTPStatus_t addContentLengthHeader ( HTTPRequestHeaders_t pRequestHeaders,
size_t  contentLength 
)
static

Adds the Content-Length header field and value to the pRequestHeaders.

Parameters
[in]pRequestHeadersRequest header buffer information.
[in]contentLengthThe Content-Length header value to write.
Returns
HTTPSuccess if successful. If there was insufficient memory in the application buffer, then HTTPInsufficientMemory is returned.

◆ sendHttpBody()

static HTTPStatus_t sendHttpBody ( const TransportInterface_t pTransport,
HTTPClient_GetCurrentTimeFunc_t  getTimestampMs,
const uint8_t *  pRequestBodyBuf,
size_t  reqBodyBufLen 
)
static

Send the HTTP body over the transport send interface.

Parameters
[in]pTransportTransport interface.
[in]getTimestampMsFunction to retrieve a timestamp in milliseconds.
[in]pRequestBodyBufRequest body buffer.
[in]reqBodyBufLenLength of the request body buffer.
Returns
HTTPSuccess if successful. If there was a network error or less bytes than what was specified were sent, then HTTPNetworkError is returned.

◆ httpHeaderStrncpy()

static char * httpHeaderStrncpy ( char *  pDest,
const char *  pSrc,
size_t  len,
uint8_t  isField 
)
static

A strncpy replacement with HTTP header validation.

This function checks for \r and \n in the pSrc while copying. This function checks for : in the pSrc, if isField is set to 1.

Parameters
[in]pDestThe destination buffer to copy to.
[in]pSrcThe source buffer to copy from.
[in]lenThe length of pSrc to copy to pDest.
[in]isFieldSet to 0 to indicate that pSrc is a field. Set to 1 to indicate that pSrc is a value.
Returns
pDest if the copy was successful, NULL otherwise.

◆ addHeader()

static HTTPStatus_t addHeader ( HTTPRequestHeaders_t pRequestHeaders,
const char *  pField,
size_t  fieldLen,
const char *  pValue,
size_t  valueLen 
)
static

Write header based on parameters. This method also adds a trailing "\r\n". If a trailing "\r\n" already exists in the HTTP header, this method backtracks in order to write over it and updates the length accordingly.

Parameters
[in]pRequestHeadersRequest header buffer information.
[in]pFieldThe ISO 8859-1 encoded header field name to write.
[in]fieldLenThe byte length of the header field name.
[in]pValueThe ISO 8859-1 encoded header value to write.
[in]valueLenThe byte length of the header field value.
Returns
HTTPSuccess if successful. If there was insufficient memory in the application buffer, then HTTPInsufficientMemory is returned.

◆ addRangeHeader()

static HTTPStatus_t addRangeHeader ( HTTPRequestHeaders_t pRequestHeaders,
int32_t  rangeStartOrlastNbytes,
int32_t  rangeEnd 
)
static

Add the byte range request header to the request headers store in HTTPRequestHeaders_t.pBuffer once all the parameters are validated.

Parameters
[in]pRequestHeadersRequest header buffer information.
[in]rangeStartOrlastNbytesRepresents either the starting byte for a range OR the last N number of bytes in the requested file.
[in]rangeEndThe 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.
Returns
HTTPSuccess if successful. If there was insufficient memory in the application buffer, then HTTPInsufficientMemory is returned.

◆ getFinalResponseStatus()

static HTTPStatus_t getFinalResponseStatus ( HTTPParsingState_t  parsingState,
size_t  totalReceived,
size_t  responseBufferLen 
)
static

Get the status of the HTTP response given the parsing state and how much data is in the response buffer.

Parameters
[in]parsingStateState of the parsing on the HTTP response.
[in]totalReceivedThe amount of network data received in the response buffer.
[in]responseBufferLenThe length of the response buffer.
Returns
Returns HTTPSuccess if the parsing state is complete. If the parsing state denotes it never started, then return HTTPNoResponse. If the parsing state is incomplete, then if the response buffer is not full HTTPPartialResponse is returned. If the parsing state is incomplete, then if the response buffer is full HTTPInsufficientMemory is returned.

◆ receiveAndParseHttpResponse()

static HTTPStatus_t receiveAndParseHttpResponse ( const TransportInterface_t pTransport,
HTTPResponse_t pResponse,
const HTTPRequestHeaders_t pRequestHeaders 
)
static

Receive the HTTP response from the network and parse it.

Parameters
[in]pTransportTransport interface.
[in]pResponseResponse message to receive data from the network.
[in]pRequestHeadersRequest headers for the corresponding HTTP request.
Returns
Returns HTTPSuccess if successful. HTTPNetworkError for a transport receive error. Please see parseHttpResponse and getFinalResponseStatus for other statuses returned.

◆ sendHttpRequest()

static HTTPStatus_t sendHttpRequest ( const TransportInterface_t pTransport,
HTTPClient_GetCurrentTimeFunc_t  getTimestampMs,
HTTPRequestHeaders_t pRequestHeaders,
const uint8_t *  pRequestBodyBuf,
size_t  reqBodyBufLen,
uint32_t  sendFlags 
)
static

Send the HTTP request over the network.

Parameters
[in]pTransportTransport interface.
[in]getTimestampMsFunction to retrieve a timestamp in milliseconds.
[in]pRequestHeadersRequest headers to send over the network.
[in]pRequestBodyBufRequest body buffer to send over the network.
[in]reqBodyBufLenLength of the request body buffer.
[in]sendFlagsApplication provided flags to HTTPClient_Send.
Returns
Returns HTTPSuccess if successful. Please see sendHttpHeaders and sendHttpBody for other statuses returned.

◆ convertInt32ToAscii()

static uint8_t convertInt32ToAscii ( int32_t  value,
char *  pBuffer,
size_t  bufferLength 
)
static

Converts an integer value to its ASCII representation in the passed buffer.

Parameters
[in]valueThe value to convert to ASCII.
[out]pBufferThe buffer to store the ASCII representation of the integer.
[in]bufferLengthThe length of pBuffer.
Returns
Returns the number of bytes written to pBuffer.

◆ writeRequestLine()

static HTTPStatus_t writeRequestLine ( HTTPRequestHeaders_t pRequestHeaders,
const char *  pMethod,
size_t  methodLen,
const char *  pPath,
size_t  pathLen 
)
static

This method writes the request line (first line) of the HTTP Header into HTTPRequestHeaders_t.pBuffer and updates length accordingly.

Parameters
pRequestHeadersRequest header buffer information.
pMethodThe HTTP request method e.g. "GET", "POST", "PUT", or "HEAD".
methodLenThe byte length of the request method.
pPathThe Request-URI to the objects of interest, e.g. "/path/to/item.txt".
pathLenThe byte length of the request path.
Returns
HTTPSuccess if successful. If there was insufficient memory in the application buffer, then HTTPInsufficientMemory is returned.

◆ findHeaderInResponse()

static HTTPStatus_t findHeaderInResponse ( const uint8_t *  pBuffer,
size_t  bufferLen,
const char *  pField,
size_t  fieldLen,
const char **  pValueLoc,
size_t *  pValueLen 
)
static

Find the specified header field in the response buffer.

Parameters
[in]pBufferThe response buffer to parse.
[in]bufferLenThe length of the response buffer to parse.
[in]pFieldThe header field to search for.
[in]fieldLenThe length of pField.
[out]pValueLocThe location of the the header value found in pBuffer.
[out]pValueLenThe length of pValue.
Returns
One of the following:

◆ findHeaderFieldParserCallback()

static int findHeaderFieldParserCallback ( http_parser *  pHttpParser,
const char *  pFieldLoc,
size_t  fieldLen 
)
static

The "on_header_field" callback for the HTTP parser used by the findHeaderInResponse function. The callback checks whether the parser header field matched the header being searched for, and sets a flag to represent reception of the header accordingly.

Parameters
[in]pHttpParserParsing object containing state and callback context.
[in]pFieldLocThe location of the parsed header field in the response buffer.
[in]fieldLenThe length of the header field.
Returns
Returns HTTP_PARSER_CONTINUE_PARSING to indicate continuation with parsing.

◆ findHeaderValueParserCallback()

static int findHeaderValueParserCallback ( http_parser *  pHttpParser,
const char *  pValueLoc,
size_t  valueLen 
)
static

The "on_header_value" callback for the HTTP parser used by the findHeaderInResponse function. The callback sets the user-provided output parameters for header value if the requested header's field was found in the findHeaderFieldParserCallback function.

Parameters
[in]pHttpParserParsing object containing state and callback context.
[in]pValueLocThe location of the parsed header value in the response buffer.
[in]valueLenThe length of the header value.
Returns
Returns HTTP_PARSER_STOP_PARSING, if the header field/value pair are found, otherwise HTTP_PARSER_CONTINUE_PARSING is returned.

◆ findHeaderOnHeaderCompleteCallback()

static int findHeaderOnHeaderCompleteCallback ( http_parser *  pHttpParser)
static

The "on_header_complete" callback for the HTTP parser used by the findHeaderInResponse function.

This callback will only be invoked if the requested header is not found in the response. This callback is used to signal the parser to halt execution if the requested header is not found.

Parameters
[in]pHttpParserParsing object containing state and callback context.
Returns
Returns HTTP_PARSER_STOP_PARSING for the parser to halt further execution, as all headers have been parsed in the response.

◆ initializeParsingContextForFirstResponse()

static void initializeParsingContextForFirstResponse ( HTTPParsingContext_t pParsingContext,
const HTTPRequestHeaders_t pRequestHeaders 
)
static

Initialize the parsing context for parsing a response fresh from the server.

Parameters
[in]pParsingContextThe parsing context to initialize.
[in]pRequestHeadersRequest headers for the corresponding HTTP request.

◆ parseHttpResponse()

static HTTPStatus_t parseHttpResponse ( HTTPParsingContext_t pParsingContext,
HTTPResponse_t pResponse,
size_t  parseLen 
)
static

Parses the response buffer in pResponse.

This function may be invoked multiple times for different parts of the the HTTP response. The state of what was last parsed in the response is kept in pParsingContext.

Parameters
[in,out]pParsingContextThe response parsing state.
[in,out]pResponseThe response information to be updated.
[in]parseLenThe next length to parse in pResponse->pBuffer.
Returns
One of the following:

◆ httpParserOnMessageBeginCallback()

static int httpParserOnMessageBeginCallback ( http_parser *  pHttpParser)
static

Callback invoked during http_parser_execute() to indicate the start of the HTTP response message.

This callback is invoked when an "H" in the "HTTP/1.1" that starts a response is found.

Parameters
[in]pHttpParserParsing object containing state and callback context.
Returns
HTTP_PARSER_CONTINUE_PARSING to continue parsing.

◆ httpParserOnStatusCallback()

static int httpParserOnStatusCallback ( http_parser *  pHttpParser,
const char *  pLoc,
size_t  length 
)
static

Callback invoked during http_parser_execute() when the HTTP response status-code and its associated reason-phrase are found.

Parameters
[in]pHttpParserParsing object containing state and callback context.
[in]pLocLocation of the HTTP response reason-phrase string in the response message buffer.
[in]lengthLength of the HTTP response status code string.
Returns
HTTP_PARSER_CONTINUE_PARSING to continue parsing.

◆ httpParserOnHeaderFieldCallback()

static int httpParserOnHeaderFieldCallback ( http_parser *  pHttpParser,
const char *  pLoc,
size_t  length 
)
static

Callback invoked during http_parser_execute() when an HTTP response header field is found.

If only part of the header field was found, then parsing of the next part of the response message will invoke this callback in succession.

Parameters
[in]pHttpParserParsing object containing state and callback context.
[in]pLocLocation of the header field string in the response message buffer.
[in]lengthLength of the header field.
Returns
HTTP_PARSER_CONTINUE_PARSING to continue parsing.

◆ httpParserOnHeaderValueCallback()

static int httpParserOnHeaderValueCallback ( http_parser *  pHttpParser,
const char *  pLoc,
size_t  length 
)
static

Callback invoked during http_parser_execute() when an HTTP response header value is found.

This header value corresponds to the header field that was found in the immediately preceding httpParserOnHeaderFieldCallback().

If only part of the header value was found, then parsing of the next part of the response message will invoke this callback in succession.

Parameters
[in]pHttpParserParsing object containing state and callback context.
[in]pLocLocation of the header value in the response message buffer.
[in]lengthLength of the header value.
Returns
HTTP_PARSER_CONTINUE_PARSING to continue parsing.

◆ httpParserOnHeadersCompleteCallback()

static int httpParserOnHeadersCompleteCallback ( http_parser *  pHttpParser)
static

Callback invoked during http_parser_execute() when the end of the headers are found.

The end of the headers is signaled in a HTTP response message by another "\r\n" after the final header line.

Parameters
[in]pHttpParserParsing object containing state and callback context.
Returns
HTTP_PARSER_CONTINUE_PARSING to continue parsing. HTTP_PARSER_STOP_PARSING is returned if the response is for a HEAD request.

◆ httpParserOnBodyCallback()

static int httpParserOnBodyCallback ( http_parser *  pHttpParser,
const char *  pLoc,
size_t  length 
)
static

Callback invoked during http_parser_execute() when the HTTP response body is found.

If only part of the response body was found, then parsing of the next part of the response message will invoke this callback in succession.

This callback will be also invoked in succession if the response body is of type "Transfer-Encoding: chunked". This callback will be invoked after each chunk header.

The follow is an example of a Transfer-Encoding chunked response:

HTTP/1.1 200 OK\r\n
Content-Type: text/plain\r\n
Transfer-Encoding: chunked\r\n
\r\n
d\r\n
Hello World! \r\n
7\r\n
I am a \r\n
a\r\n
developer.\r\n
0\r\n
\r\n

The first invocation of this callback will contain pLoc = "Hello World!" and length = 13. The second invocation of this callback will contain pLoc = "I am a " and length = 7. The third invocation of this callback will contain pLoc = "developer." and length = 10.

Parameters
[in]pHttpParserParsing object containing state and callback context.
[in]pLoc- Pointer to the body string in the response message buffer.
[in]length- The length of the body found.
Returns
Zero to continue parsing. All other return values will stop parsing and http_parser_execute() will return with status HPE_CB_body.

◆ httpParserOnMessageCompleteCallback()

static int httpParserOnMessageCompleteCallback ( http_parser *  pHttpParser)
static

Callback invoked during http_parser_execute() to indicate the the completion of an HTTP response message.

When there is no response body, the end of the response message is when the headers end. This is indicated by another "\r\n" after the final header line.

When there is response body, the end of the response message is when the full "Content-Length" value is parsed following the end of the headers. If there is no Content-Length header, then http_parser_execute() expects a zero length-ed parsing data to indicate the end of the response.

For a "Transfer-Encoding: chunked" type of response message, the complete response message is signaled by a terminating chunk header with length zero.

See https://github.com/nodejs/http-parser for more information.

Parameters
[in]pHttpParserParsing object containing state and callback context.
Returns
Zero to continue parsing. All other return values will stop parsing and http_parser_execute() will return with status HPE_CB_message_complete.

◆ processCompleteHeader()

static void processCompleteHeader ( HTTPParsingContext_t pParsingContext)
static

When a complete header is found the HTTP response header count increases and the application is notified.

This function is invoked only in callbacks that could follow httpParserOnHeaderValueCallback. These callbacks are httpParserOnHeaderFieldCallback and httpParserOnHeadersCompleteCallback. A header field and value is not is not known to be complete until httpParserOnHeaderValueCallback is not called in succession.

Parameters
[in]pParsingContextParsing state containing information to notify the application of a complete header.

◆ processHttpParserError()

static HTTPStatus_t processHttpParserError ( const http_parser *  pHttpParser)
static

When parsing is complete an error could be indicated in pHttpParser->http_errno. This function translates that error into a library specific error code.

Parameters
[in]pHttpParserThird-party HTTP parsing context.
Returns
One of the following:

◆ caseInsensitiveStringCmp()

static int8_t caseInsensitiveStringCmp ( const char *  str1,
const char *  str2,
size_t  n 
)
static

Compares at most the first n bytes of str1 and str2 without case sensitivity and n must be less than the actual size of either string.

Parameters
[in]str1First string to be compared.
[in]str2Second string to be compared.
[in]nThe maximum number of characters to be compared.
Returns
One of the following: 0 if str1 is equal to str2 1 if str1 is not equal to str2.

◆ HTTPClient_InitializeRequestHeaders()

HTTPStatus_t HTTPClient_InitializeRequestHeaders ( HTTPRequestHeaders_t pRequestHeaders,
const HTTPRequestInfo_t pRequestInfo 
)

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.

Parameters
[in]pRequestHeadersRequest header buffer information.
[in]pRequestInfoInitial request header configurations.
Returns
One of the following:

Example

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;
httpLibraryStatus = HTTPClient_InitializeRequestHeaders( &requestHeaders,
&requestInfo );
HTTPStatus_t HTTPClient_InitializeRequestHeaders(HTTPRequestHeaders_t *pRequestHeaders, const HTTPRequestInfo_t *pRequestInfo)
Initialize the request headers, stored in HTTPRequestHeaders_t.pBuffer, with initial configurations f...
Definition: core_http_client.c:1557
#define HTTP_METHOD_GET
Definition: core_http_client.h:60
HTTPStatus_t
The HTTP Client library return status.
Definition: core_http_client.h:162
@ HTTPSuccess
The HTTP Client library function completed successfully.
Definition: core_http_client.h:173
#define HTTP_REQUEST_KEEP_ALIVE_FLAG
Set this flag to indicate that the request is for a persistent connection.
Definition: core_http_client.h:112
Represents header data that will be sent in an HTTP request.
Definition: core_http_client.h:329
size_t bufferLen
Definition: core_http_client.h:345
uint8_t * pBuffer
Buffer to hold the raw HTTP request headers.
Definition: core_http_client.h:344
Configurations of the initial request headers.
Definition: core_http_client.h:360
uint32_t reqFlags
Flags to activate other request header configurations.
Definition: core_http_client.h:386
size_t methodLen
Definition: core_http_client.h:365
const char * pMethod
The HTTP request method e.g. "GET", "POST", "PUT", or "HEAD".
Definition: core_http_client.h:364
const char * pPath
The Request-URI to the objects of interest, e.g. "/path/to/item.txt".
Definition: core_http_client.h:370
const char * pHost
The server's host name, e.g. "my-storage.my-cloud.com".
Definition: core_http_client.h:378
size_t pathLen
Definition: core_http_client.h:371
size_t hostLen
Definition: core_http_client.h:379

◆ HTTPClient_AddHeader()

HTTPStatus_t HTTPClient_AddHeader ( HTTPRequestHeaders_t pRequestHeaders,
const char *  pField,
size_t  fieldLen,
const char *  pValue,
size_t  valueLen 
)

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:

<field>: <value>\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.

Note
This function validates only that \r, \n, and : are not present in pValue or pField. : is allowed in pValue.
Parameters
[in]pRequestHeadersRequest header buffer information.
[in]pFieldThe 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.
[in]fieldLenThe byte length of the header field name.
[in]pValueThe 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.
[in]valueLenThe byte length of the header field value.
Returns
One of the following:

Example

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 );
HTTPStatus_t HTTPClient_AddHeader(HTTPRequestHeaders_t *pRequestHeaders, const char *pField, size_t fieldLen, const char *pValue, size_t valueLen)
Add a header to the request headers stored in HTTPRequestHeaders_t.pBuffer.
Definition: core_http_client.c:1654

◆ HTTPClient_AddRangeHeader()

HTTPStatus_t HTTPClient_AddRangeHeader ( HTTPRequestHeaders_t pRequestHeaders,
int32_t  rangeStartOrlastNbytes,
int32_t  rangeEnd 
)

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 rangeStartOrLastNBytes and rangeEnd parameter values:

  1. Request containing both parameters for the byte range [rangeStart, rangeEnd] where rangeStartOrLastNBytes <= rangeEnd. Example request header line: Range: bytes=0-1023\r\n for requesting bytes in the range [0, 1023].
    Example
    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 );
    HTTPStatus_t HTTPClient_AddRangeHeader(HTTPRequestHeaders_t *pRequestHeaders, int32_t rangeStartOrlastNbytes, int32_t rangeEnd)
    Add the byte range request header to the request headers store in HTTPRequestHeaders_t....
    Definition: core_http_client.c:1714
  2. Request for the last N bytes, represented by rangeStartOrlastNbytes. rangeStartOrlastNbytes should be negative and 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).
    Example
    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)
    #define HTTP_RANGE_REQUEST_END_OF_FILE
    Flag that represents End of File byte in the range specification of a Range Request....
    Definition: core_http_client.h:155
  3. Request for all bytes (till the end of byte sequence) from byte N, represented by rangeStartOrlastNbytes. rangeStartOrlastNbytes should be >= 0 and rangeEnd should be HTTP_RANGE_REQUEST_END_OF_FILE.
    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).
    Example
    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)
Parameters
[in]pRequestHeadersRequest header buffer information.
[in]rangeStartOrlastNbytesRepresents either the starting byte for a range OR the last N number of bytes in the requested file.
[in]rangeEndThe 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.
Returns
Returns the following status codes: HTTPSuccess, if successful. HTTPInvalidParameter, if input parameters are invalid, including when the rangeStartOrlastNbytes and rangeEnd parameter combination is invalid. HTTPInsufficientMemory, if the passed HTTPRequestHeaders_t.pBuffer contains insufficient remaining memory for storing the range request.

◆ 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 
)

Send the request headers in HTTPRequestHeaders_t.pBuffer and request body in pRequestBodyBuf over the transport. The response is received in HTTPResponse_t.pBuffer.

If HTTP_SEND_DISABLE_CONTENT_LENGTH_FLAG is not set in parameter sendFlags, then the Content-Length to be sent to the server is automatically written to 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:

The pResponse returned is valid only if this function returns HTTPSuccess.

Parameters
[in]pTransportTransport interface, see TransportInterface_t for more information.
[in]pRequestHeadersRequest configuration containing the buffer of headers to send.
[in]pRequestBodyBufOptional Request entity body. Set to NULL if there is no request body.
[in]reqBodyBufLenThe length of the request entity in bytes.
[in]pResponseThe response message and some notable response parameters will be returned here on success.
[in]sendFlagsFlags which modify the behavior of this function. Please see HTTPClient_Send Flags for more information.
Returns
One of the following:

Example

// Variables used in this example.
HTTPStatus_t httpLibraryStatus = HTTPSuccess;
TransportInterface_t transportInterface = { 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.
}
}
HTTPStatus_t HTTPClient_Send(const TransportInterface_t *pTransport, HTTPRequestHeaders_t *pRequestHeaders, const uint8_t *pRequestBodyBuf, size_t reqBodyBufLen, HTTPResponse_t *pResponse, uint32_t sendFlags)
Send the request headers in HTTPRequestHeaders_t.pBuffer and request body in pRequestBodyBuf over the...
Definition: core_http_client.c:2154
Represents an HTTP response.
Definition: core_http_client.h:434
The transport layer interface.
Definition: transport_interface.h:252
TransportSend_t send
Definition: transport_interface.h:254
TransportRecv_t recv
Definition: transport_interface.h:253
NetworkContext_t * pNetworkContext
Definition: transport_interface.h:255

◆ HTTPClient_ReadHeader()

HTTPStatus_t HTTPClient_ReadHeader ( const HTTPResponse_t pResponse,
const char *  pField,
size_t  fieldLen,
const char **  pValueLoc,
size_t *  pValueLen 
)

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 pValue. If the header value is empty for the found pField, then this function will return HTTPSuccess, and set the values for pValueLoc and 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.
Parameters
[in]pResponseThe buffer containing the completed HTTP response.
[in]pFieldThe header field name to read.
[in]fieldLenThe length of the header field name in bytes.
[out]pValueLocThis will be populated with the location of the header value in the response buffer, HTTPResponse_t.pBuffer.
[out]pValueLenThis will be populated with the length of the header value in bytes.
Returns
One of the following:

Example

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 );
HTTPStatus_t HTTPClient_ReadHeader(const HTTPResponse_t *pResponse, const char *pField, size_t fieldLen, const char **pValueLoc, size_t *pValueLen)
Read a header from a buffer containing a complete HTTP response. This will return the location of the...
Definition: core_http_client.c:2496

◆ HTTPClient_strerror()

const char * HTTPClient_strerror ( HTTPStatus_t  status)

Error code to string conversion utility for HTTP Client library.

Note
This returns constant strings, which should not be modified.
Parameters
[in]statusThe status code to convert to a string.
Returns
The string representation of the status code.