coreHTTP v3.1.1
HTTP/1.1 Client Library
 
Loading...
Searching...
No Matches
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.
 
static HTTPStatus_t addContentLengthHeader (HTTPRequestHeaders_t *pRequestHeaders, size_t contentLength)
 Adds the Content-Length header field and value to the pRequestHeaders.
 
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.
 
static char * httpHeaderStrncpy (char *pDest, const char *pSrc, size_t len, uint8_t isField)
 A strncpy replacement with HTTP header validation.
 
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.
 
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.
 
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.
 
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.
 
static uint8_t convertInt32ToAscii (int32_t value, char *pBuffer, size_t bufferLength)
 Converts an integer value to its ASCII representation in the passed buffer.
 
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.
 
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.
 
static int findHeaderFieldParserCallback (llhttp_t *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.
 
static int findHeaderValueParserCallback (llhttp_t *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.
 
static int findHeaderOnHeaderCompleteCallback (llhttp_t *pHttpParser)
 The "on_header_complete" callback for the HTTP parser used by the findHeaderInResponse function.
 
static void initializeParsingContextForFirstResponse (HTTPParsingContext_t *pParsingContext, const HTTPRequestHeaders_t *pRequestHeaders)
 Initialize the parsing context for parsing a response fresh from the server.
 
static HTTPStatus_t parseHttpResponse (HTTPParsingContext_t *pParsingContext, HTTPResponse_t *pResponse, size_t parseLen)
 Parses the response buffer in pResponse.
 
static int httpParserOnMessageBeginCallback (llhttp_t *pHttpParser)
 Callback invoked during llhttp_execute() to indicate the start of the HTTP response message.
 
static int httpParserOnStatusCallback (llhttp_t *pHttpParser, const char *pLoc, size_t length)
 Callback invoked during llhttp_execute() when the HTTP response status-code and its associated reason-phrase are found.
 
static int httpParserOnStatusCompleteCallback (llhttp_t *pHttpParser)
 Callback invoked during llhttp_execute() when the HTTP response status parsing is complete.
 
static int httpParserOnHeaderFieldCallback (llhttp_t *pHttpParser, const char *pLoc, size_t length)
 Callback invoked during llhttp_execute() when an HTTP response header field is found.
 
static int httpParserOnHeaderValueCallback (llhttp_t *pHttpParser, const char *pLoc, size_t length)
 Callback invoked during llhttp_execute() when an HTTP response header value is found.
 
static int httpParserOnHeadersCompleteCallback (llhttp_t *pHttpParser)
 Callback invoked during llhttp_execute() when the end of the headers are found.
 
static int httpParserOnBodyCallback (llhttp_t *pHttpParser, const char *pLoc, size_t length)
 Callback invoked during llhttp_execute() when the HTTP response body is found.
 
static int httpParserOnMessageCompleteCallback (llhttp_t *pHttpParser)
 Callback invoked during llhttp_execute() to indicate the the completion of an HTTP response message.
 
static void processCompleteHeader (HTTPParsingContext_t *pParsingContext)
 When a complete header is found the HTTP response header count increases and the application is notified.
 
static HTTPStatus_t processLlhttpError (const llhttp_t *pHttpParser)
 When parsing is complete an error could be indicated in pHttpParser->error. This function translates that error into a library specific error code.
 
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.
 
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.
 
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.
 
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.
 
HTTPStatus_t HTTPClient_SendHttpData (const TransportInterface_t *pTransport, HTTPClient_GetCurrentTimeFunc_t getTimestampMs, const uint8_t *pData, size_t dataLen)
 Send the request body in pRequestBodyBuf over the transport.
 
HTTPStatus_t HTTPClient_SendHttpHeaders (const TransportInterface_t *pTransport, HTTPClient_GetCurrentTimeFunc_t getTimestampMs, HTTPRequestHeaders_t *pRequestHeaders, size_t reqBodyLen, uint32_t sendFlags)
 Send the request headers in pRequestHeaders over the transport.
 
HTTPStatus_t HTTPClient_ReceiveAndParseHttpResponse (const TransportInterface_t *pTransport, HTTPResponse_t *pResponse, const HTTPRequestHeaders_t *pRequestHeaders)
 Receive the HTTP response from the network and parse it.
 
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.
 
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.
 
const char * HTTPClient_strerror (HTTPStatus_t status)
 Error code to string conversion utility for HTTP Client library.
 

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.

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

◆ 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 HTTPClient_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 ( llhttp_t *  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 LLHTTP_CONTINUE_PARSING to indicate continuation with parsing.

◆ findHeaderValueParserCallback()

static int findHeaderValueParserCallback ( llhttp_t *  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 LLHTTP_STOP_PARSING, if the header field/value pair are found, otherwise LLHTTP_CONTINUE_PARSING is returned.

◆ findHeaderOnHeaderCompleteCallback()

static int findHeaderOnHeaderCompleteCallback ( llhttp_t *  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 LLHTTP_STOP_PARSING_NO_HEADER 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 ( llhttp_t *  pHttpParser)
static

Callback invoked during llhttp_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
LLHTTP_CONTINUE_PARSING to continue parsing.

◆ httpParserOnStatusCallback()

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

Callback invoked during llhttp_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
LLHTTP_CONTINUE_PARSING to continue parsing.

◆ httpParserOnStatusCompleteCallback()

static int httpParserOnStatusCompleteCallback ( llhttp_t *  pHttpParser)
static

Callback invoked during llhttp_execute() when the HTTP response status parsing is complete.

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

◆ httpParserOnHeaderFieldCallback()

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

Callback invoked during llhttp_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
LLHTTP_CONTINUE_PARSING to continue parsing.

◆ httpParserOnHeaderValueCallback()

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

Callback invoked during llhttp_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
LLHTTP_CONTINUE_PARSING to continue parsing.

◆ httpParserOnHeadersCompleteCallback()

static int httpParserOnHeadersCompleteCallback ( llhttp_t *  pHttpParser)
static

Callback invoked during llhttp_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
LLHTTP_CONTINUE_PARSING to continue parsing. LLHTTP_STOP_PARSING_NO_BODY is returned if the response is for a HEAD request.

◆ httpParserOnBodyCallback()

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

Callback invoked during llhttp_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 llhttp_execute() will return with the same value.

◆ httpParserOnMessageCompleteCallback()

static int httpParserOnMessageCompleteCallback ( llhttp_t *  pHttpParser)
static

Callback invoked during llhttp_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 llhttp_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/llhttp 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 llhttp_execute() will return with the same value.

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

◆ processLlhttpError()

static HTTPStatus_t processLlhttpError ( const llhttp_t *  pHttpParser)
static

When parsing is complete an error could be indicated in pHttpParser->error. 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:1589
#define HTTP_METHOD_GET
Definition: core_http_client.h:62
HTTPStatus_t
The HTTP Client library return status.
Definition: core_http_client.h:196
@ HTTPSuccess
The HTTP Client library function completed successfully.
Definition: core_http_client.h:207
#define HTTP_REQUEST_KEEP_ALIVE_FLAG
Set this flag to indicate that the request is for a persistent connection.
Definition: core_http_client.h:114
Represents header data that will be sent in an HTTP request.
Definition: core_http_client.h:365
size_t bufferLen
Definition: core_http_client.h:381
uint8_t * pBuffer
Buffer to hold the raw HTTP request headers.
Definition: core_http_client.h:380
Configurations of the initial request headers.
Definition: core_http_client.h:396
uint32_t reqFlags
Flags to activate other request header configurations.
Definition: core_http_client.h:422
size_t methodLen
Definition: core_http_client.h:401
const char * pMethod
The HTTP request method e.g. "GET", "POST", "PUT", or "HEAD".
Definition: core_http_client.h:400
const char * pPath
The Request-URI to the objects of interest, e.g. "/path/to/item.txt".
Definition: core_http_client.h:406
const char * pHost
The server's host name, e.g. "my-storage.my-cloud.com".
Definition: core_http_client.h:414
size_t pathLen
Definition: core_http_client.h:407
size_t hostLen
Definition: core_http_client.h:415

◆ 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:1689

◆ 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:1749
  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:189
  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_SendHttpData()

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

Send the request body in pRequestBodyBuf over the transport.

Parameters
[in]pTransportTransport interface, see TransportInterface_t for more information.
[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.

◆ HTTPClient_SendHttpHeaders()

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

Send the request headers in pRequestHeaders over the transport.

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:

Parameters
[in]pTransportTransport interface, see TransportInterface_t for more information.
[in]getTimestampMsFunction to retrieve a timestamp in milliseconds.
[in]pRequestHeadersRequest configuration containing the buffer of headers to send.
[in]reqBodyLenThe length of the request entity in bytes.
[in]sendFlagsFlags which modify the behavior of this function. Please see HTTPClient_Send Flags for more information.
Returns
HTTPSuccess if successful. If there was a network error or less bytes than what were specified were sent, then HTTPNetworkError is returned.

◆ HTTPClient_ReceiveAndParseHttpResponse()

HTTPStatus_t HTTPClient_ReceiveAndParseHttpResponse ( const TransportInterface_t pTransport,
HTTPResponse_t pResponse,
const HTTPRequestHeaders_t pRequestHeaders 
)

Receive the HTTP response from the network and parse it.

Parameters
[in]pTransportTransport interface, see TransportInterface_t for more information.
[in]pResponseThe response message and some notable response parameters will be returned here on success.
[in]pRequestHeadersRequest configuration containing the buffer of headers to send.
Returns
Returns HTTPSuccess if successful. HTTPNetworkError for a transport receive error. Please see parseHttpResponse and getFinalResponseStatus for other statuses returned.

◆ 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:2209
Represents an HTTP response.
Definition: core_http_client.h:470
The transport layer interface.
Definition: transport_interface.h:299
TransportSend_t send
Definition: transport_interface.h:301
TransportRecv_t recv
Definition: transport_interface.h:300
NetworkContext_t * pNetworkContext
Definition: transport_interface.h:303

◆ 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:2553

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