HTTP Server API#

HTTPs_ConfigureMemSeg()#

Description#

Configure the memory segment that will be used to allocate internal data needed by the HTTP server module instead of the default memory segment.

Files#

http_server.h/http_server.c

Prototype#

void  HTTPs_ConfigureMemSeg (MEM_SEG  *p_mem_seg)

Arguments#

p_mem_seg

Pointer to the memory segment from which the internal data will be allocated. If DEF_NULL, the internal data will be allocated from the global Heap.

Returned Value#

None.

Notes / Warnings#

  1. This function is optional. If it is called, it must be called before HTTPs_Init(). If it is not called, default values will be used to initialize the module.

HTTPs_Init()#

Description#

Initializes the HTTP server suite.

Files#

http_server.h/http_server.c

Prototype#

void  HTTPs_Init (RTOS_ERR  *p_err)

Arguments#

p_err

Pointer to the variable that will receive one of the following error code(s) from this function :

  • RTOS_ERR_NONE

  • RTOS_ERR_ALREADY_INIT

  • RTOS_ERR_BLK_ALLOC_CALLBACK

  • RTOS_ERR_SEG_OVF

Returned Value#

None.

Notes / Warnings#

None.

HTTPs_InstanceInit()#

Description#

Initializes an HTTP server instance.

Files#

http_server.h/http_server.c

Prototype#

HTTPs_INSTANCE  *HTTPs_InstanceInit (const  HTTPs_CFG      *p_cfg,
                                     const  RTOS_TASK_CFG  *p_task_cfg,
                                            RTOS_ERR       *p_err)

Arguments#

p_cfg

Pointer to the instance configuration object.

p_task_cfg

Pointer to the instance task configuration object.

p_err

Pointer to the variable that will receive one of the following error code(s) from this function :

  • RTOS_ERR_NONE

  • RTOS_ERR_NOT_READY

  • RTOS_ERR_POOL_EMPTY

  • RTOS_ERR_BLK_ALLOC_CALLBACK

  • RTOS_ERR_SEG_OVF

  • RTOS_ERR_ALLOC

  • RTOS_ERR_NOT_AVAIL

  • RTOS_ERR_OS_ILLEGAL_RUN_TIME

  • RTOS_ERR_INIT

Returned Value#

  • Pointer to the instance handler, if NO error(s).

  • NULL pointer, otherwise.

Notes / Warnings#

None.

HTTPs_InstanceTaskPrioSet()#

Description#

Sets the priority of the given HTTP server instance's task.

Files#

http_server.h/http_server.c

Prototype#

void  HTTPs_InstanceTaskPrioSet (HTTPs_INSTANCE  *p_instance,
                                 RTOS_TASK_PRIO   prio,
                                 RTOS_ERR        *p_err)

Arguments#

p_instance

Pointer to specific HTTP server instance handler.

prio

Priority of the HTTP instance's task.

p_err

Pointer to the variable that will receive one of the following error code(s) from this function :

  • RTOS_ERR_NONE

  • RTOS_ERR_INVALID_ARG

Returned Value#

None.

Notes / Warnings#

None.

HTTPs_InstanceStart()#

Description#

Starts a specific HTTPs server instance which had been previously initialized.

Files#

http_server.h/http_server.c

Prototype#

void  HTTPs_InstanceStart (HTTPs_INSTANCE  *p_instance,
                           RTOS_ERR        *p_err)

Arguments#

p_instance

Pointer to specific HTTP server instance handler.

p_err

Pointer to the variable that will receive one of the following error code(s) from this function :

  • RTOS_ERR_NONE

  • RTOS_ERR_OS_ILLEGAL_RUN_TIME

  • RTOS_ERR_INVALID_TYPE

  • RTOS_ERR_POOL_EMPTY

  • RTOS_ERR_NOT_FOUND

  • RTOS_ERR_ALREADY_EXISTS

  • RTOS_ERR_INVALID_HANDLE

  • RTOS_ERR_NET_INVALID_CONN

  • RTOS_ERR_INVALID_STATE

  • RTOS_ERR_NET_CONN_CLOSED_FAULT

Returned Value#

None.

Notes / Warnings#

None.

HTTPs_InstanceStop()#

Description#

Stops a specific HTTPs server instance.

Files#

http_server.h/http_server.c

Prototype#

void  HTTPs_InstanceStop (HTTPs_INSTANCE  *p_instance,
                          RTOS_ERR        *p_err)

Arguments#

p_instance

Pointer to Instance handler.

p_err

Pointer to the variable that will receive one of the following error code(s) from this function :

  • RTOS_ERR_NONE

  • RTOS_ERR_OS_OBJ_DEL

  • RTOS_ERR_WOULD_BLOCK

  • RTOS_ERR_OS_SCHED_LOCKED

  • RTOS_ERR_ABORT

  • RTOS_ERR_TIMEOUT

Returned Value#

None.

Notes / Warnings#

None.

HTTPs_RespBodySetParamFile()#

Description#

Sets the parameters for the response body when the body's data is a file inside a File System infrastructure.

Files#

http_server.h/http_server.c

Prototype#

void  HTTPs_RespBodySetParamFile (const  HTTPs_INSTANCE        *p_instance,
                                         HTTPs_CONN            *p_conn,
                                         CPU_CHAR              *p_path,
                                         HTTP_CONTENT_TYPE      content_type,
                                         CPU_BOOLEAN            token_en,
                                         RTOS_ERR              *p_err)

Arguments#

p_instance

Pointer to the instance.

p_conn

Pointer to the connection.

p_path

Pointer to the string file path.

content_type

Content type of the file.

If unknown, this can be set to HTTP_CONTENT_TYPE_UNKNOWN. The server core will find it with the file extension. See HTTP_CONTENT_TYPE enum in http.h for possible content types.

token_en

  • DEF_YES, if the file contents tokens the server needs to replace.

  • DEF_NO, otherwise.

p_err

Pointer to the variable that will receive one of the following error code(s) from this function :

  • RTOS_ERR_NONE

Returned Value#

None.

Notes / Warnings#

  1. Must be called from a callback function only.

(a) The instance lock must be acquired before calling this function, which is why this function must be called from a callback function.

HTTPs_RespBodySetParamNoBody()#

Description#

Sets the parameters to let the server know that no body is needed in the response.

Files#

http_server.h/http_server.c

Prototype#

void  HTTPs_RespBodySetParamNoBody (const HTTPs_INSTANCE  *p_instance,
                                          HTTPs_CONN      *p_conn,
                                          RTOS_ERR        *p_err)

Arguments#

p_instance

Pointer to the instance.

p_conn

Pointer to the connection.

p_err

Pointer to the variable that will receive one of the following error code(s) from this function :

  • RTOS_ERR_NONE

Returned Value#

None.

Notes / Warnings#

  1. Must be called from a callback function only.

    (a) The instance lock must be acquired before calling this function, which is why this function must be called from a callback function

HTTPs_RespBodySetParamStaticData()#

Description#

Sets the parameters for the response body when the body's data is a static data contained in a memory space.

Files#

http_server.h/http_server.c

Prototype#

void HTTPs_RespBodySetParamStaticData (const HTTPs_INSTANCE      *p_instance,
                                             HTTPs_CONN          *p_conn,
                                             HTTP_CONTENT_TYPE    content_type,
                                             void                *p_data,
                                             CPU_INT32U           data_len,
                                             CPU_BOOLEAN          token_en,
                                             RTOS_ERR            *p_err)

Arguments#

p_instance

Pointer to the instance.

p_conn

Pointer to the connection.

content_type

Content type of the file. See HTTP_CONTENT_TYPE enum in http.h for possible content types.

p_data

  • Pointer to memory section containing data.

  • DEF_NULL, if data will added to the response with the 'OnRespChunkHook' Hook.

data_len

Data length.

token_en

  • DEF_YES, if the data contents tokens the server needs to replace.

  • DEF_NO, otherwise.

p_err

Pointer to the variable that will receive one of the following error code(s) from this function :

  • RTOS_ERR_NONE

Returned Value#

None.

Notes / Warnings#

  1. Must be called from a callback function only.

    (a) The instance lock must be acquired before calling this function, which is why this function must be called from a callback function.

  2. This function can be used when the data to put in the response body is not in a file in a File System.

  3. If all the data to send is inside a memory space, the 'p_data' parameter can be set to point to the memory space and the 'data_len' must be set, since the data length is known.

  4. When the data to send is a stream of unknown size, the Chunked Transfer Encoding must be used. In this case, the function can work with the parameter 'p_data' when set to DEF_NULL. This tells the server to use the hook function 'p_cfg->p_hooks->OnRespChunkHook' to retrieve the data to put in the HTTP response.

HTTPs_RespHdrGet()#

Description#

Acquires a new response header block.

Files#

http_server.h/http_server.c

Prototype#

#if (HTTPs_CFG_HDR_TX_EN == DEF_ENABLED)

HTTPs_HDR_BLK *HTTPs_RespHdrGet (const HTTPs_INSTANCE      *p_instance,
                                       HTTPs_CONN          *p_conn,
                                       HTTP_HDR_FIELD       hdr_field,
                                       HTTPs_HDR_VAL_TYPE   val_type,
                                       RTOS_ERR            *p_err)

Arguments#

p_instance

Pointer to the instance.

p_conn

Pointer to the connection.

hdr_field

Type of the response header value :

See enumeration HTTPs_HDR_FIELD.

val_type

Data type of the response header field value :

  • HTTP_HDR_VAL_TYPE_NONE Header field does not require a value.

  • HTTP_HDR_VAL_TYPE_STR_CONST Header value type is a constant string.

  • HTTP_HDR_VAL_TYPE_STR Header value type is a variable string.

p_err

Pointer to the variable that will receive one of the following error code(s) from this function :

  • RTOS_ERR_NONE

  • RTOS_ERR_POOL_EMPTY

  • RTOS_ERR_BLK_ALLOC_CALLBACK

  • RTOS_ERR_SEG_OVF

Returned Value#

Pointer to the response header block that can be filled with data, if no error(s). Null pointer, otherwise

Notes / Warnings#

  1. Must be called from a callback function only. Should be called by the function pointed by RespHdrTxFnctPtr in the instance configuration.

    (a) The instance lock must be acquired before calling this function, which is is why this function must be called from a callback function.

  2. The header block is automatically added to the header blocks list, so the caller does not need to add the block to the list. Only filling the value and value length should be required by the caller.

HTTPsREST_Publish()#

Description#

Adds a REST resource to a list of resources.

Files#

http_server_rest.h/http_server_rest.c

Prototype#

void  HTTPsREST_Publish (const HTTPs_REST_RESOURCE  *p_resource,
                               CPU_INT32U            list_ID,
                               RTOS_ERR             *p_err)

Arguments#

p_resource

Pointer to the REST resource to publish.

list_ID

Identification of the list on which to publish.

p_err

Pointer to the variable that will receive one of the following error code(s) from this function :

  • RTOS_ERR_NONE

Returned Value#

None.

Notes / Warnings#

  1. Must be called after the HTTP server initialization and before HTTP server start.

HTTPs_FS_Init()#

Description#

Initializes the static file system.

Files#

http_server_fs_port_static.h/http_server_fs_port_static.c

Prototype#

CPU_BOOLEAN  HTTPs_FS_Init (void)

Arguments#

None.

Returned Value#

  • DEF_OK, if the file system was initialized.

  • DEF_FAIL, otherwise.

Notes / Warnings#

None.

HTTPs_FS_AddFile()#

Description#

Adds a file to the static file system.

Files#

http_server_fs_port_static.h/http_server_fs_port_static.c

Prototype#

CPU_BOOLEAN  HTTPs_FS_AddFile (CPU_CHAR    *p_name,
                               void        *p_data,
                               CPU_INT32U   size)

Arguments#

p_name

Name of the file.

p_data

Pointer to buffer holding file data.

size

Size of file, in octets.

Returned Value#

  • DEF_OK, if the file was added.

  • DEF_FAIL, otherwise.

Notes / Warnings#

  1. The file name must meet the following criteria:

    (a) begin with a path separator character.

    (b) be no longer than HTTPs_FS_MAX_PATH_NAME_LEN.

    (c) not end with a path separator character.

    (d) not duplicate the parent directory of a file already added.

    (e) not duplicate a file already added.

HTTPs_FS_SetTime()#

Description#

Sets the date/time of files and directories.

Files#

http_server_fs_port_static.h/http_server_fs_port_static.c

Prototype#

CPU_BOOLEAN  HTTPs_FS_SetTime (NET_FS_DATE_TIME  *p_time)

Arguments#

p_time

Pointer to date/time to set.

Returned Value#

  • DEF_OK, if the time is set.

  • DEF_FAIL, otherwise.

Notes / Warnings#

  1. This time will be returned in the directory entry for ALL files and directories.

HTTP Server Hook Functions API#

This section provides a reference to the HTTP Server Hook Functions API.

Connection Objects Initialization#

This hook function, if defined, is called by the HTTP Server every time an instance is initialized as shown in the figure HTTP Server Hook Functions . This function should be used to initialize application' objects for a web server instance. For example, this function can be used to Initialize the memory pool and chained list for a session or initialize a periodic timer that checks for expired session and release them if it is the case.

Prototype#

void  HTTPs_InstanceInitHook (const  HTTPs_INSTANCE  *p_instance,
                              const  void            *p_hook_cfg);

Arguments#

p_instance

Pointer to the instance structure (read only).

p_hook_cfg

Pointer to hook application data.

Return Values#

None.

Required Configuration#

See section Hook Configuration .

Notes / Warnings#

None.

Example Template#

Listing - HTTPs Instance Initialization Hook Example Code#
typedef  struct  HTTPs_Session  HTTPs_SESSION;
struct  HTTPs_Session{
  CPU_INT16U      SessionID;
    CLK_TS_SEC      ExpireTS;
    HTTPs_SESSION  *NextPtr;
    HTTPs_SESSION  *PrevPtr;
};

static  MEM_DYN_POOL    SessionPool;
static  HTTPs_SESSION  *SessionFirstPtr;
static  OS_TMR      SesssionIDReleaseTMR;

void  HTTPs_InstanceInitHook (const  HTTPs_INSTANCE  *p_instance,
                              const  void            *p_hook_cfg)
{
  CPU_SIZE_T  octets_reqd;
  RTOS_ERR    err;

    Mem_DynPoolCreate("HTTPs Instance Session Pool",
                      &SessionPool,                             /* Create the session memory pool.                      */
                        DEF_NULL,
                       sizeof(HTTPs_SESSION),
                       sizeof(CPU_ALIGN),
                       HTTPs_USER_LOGGED_MAX_NBR,
                       HTTPs_USER_LOGGED_MAX_NBR,
                      &err);
                                  /* Set the first pointer to NULL which indicate ...   */
    SessionFirstPtr = DEF_NULL;                                 /* there is no active session.              */

                                                                /* Create and Start the timer which check for ...       */
                                                                /* releasing expired session.                           */
    OSTmrCreate(&SesssionIDReleaseTMR,
                 HTTPs_SESSION_RELEASE_TMR_NAME_STR,
                 0,
                 OSCfg_TmrTaskRate_Hz,
                  OS_OPT_TMR_PERIODIC,
                &HTTPs_LoginReleaseSessionIDTmr,
                  DEF_NULL,
                &err);

  OSTmrStart(&SesssionIDReleaseTMR, &err);
}

Receive Request Header Field#

This hook function, if defined, is called by the HTTP Server during the parsing of a request message as shown in the figure HTTP Server Hook Functions . It allows the upper application to choose which header field must be stored to be read and used later in other hook functions.

Prototype#

void HTTPs_ReqHdrRxHook (const  HTTPs_INSTANCE   *p_instance,
                         const  HTTPs_CONN       *p_conn,
                         const  void             *p_hook_cfg,
                                HTTP_HDR_FIELD    hdr_field);

Arguments#

p_instance

Pointer to the instance structure (read only).

p_conn

Pointer to the connection structure (read only).

p_hook_cfg

Pointer to hook application data.

hdr_field

Header field type received.

Return Values#

  • DEF_YES

The header field must be processed and the value stored.

  • DEF_NO

The header field must be discarded.

Required Configuration#

HTTPs_CFG_HDR_EN configuration must be enabled in http-s_cfg.h. See section Compile-time Configurations .

The header feature must also be enabled in the Instance configuration (see section Instance Configuration ).

See section Hook Configuration .

Notes / Warnings#

  • The instance structure is for read-only. It must not be modified.

  • Connection structure should not be modified by this function it should be only read to determine if the header type must be stored.

Example Template#

The listing below is shown to demonstrate the HTTP Server module capabilities. This code simply ensures that cookies header are stored.

Listing - Request Header Received Hook Example Code#
static  CPU_BOOLEAN  HTTPs_ReqHdrRxHook (const  HTTPs_INSTANCE   *p_instance,
                                         const  HTTPs_CONN       *p_conn,
                                         const  void             *p_hook_cfg,
                                                HTTP_HDR_FIELD    hdr_field)
{
  switch (hdr_field) {
    case HTTPs_HDR_FIELD_COOKIE:
        case HTTPs_HDR_FIELD_COOKIE2:
             return(DEF_YES);

        default:
             return(DEF_NO);
  }

  return (DEF_NO);
}

Connection Request#

This hook function, if defined, is called by the HTTP Server module every time a new request has been received and processed as shown in the figure HTTP Server Hook Functions . This function can restrict the access to some resource by analyzing the connection parameter such as remote IP address, the method, resource requested, HTTP header fields, etc. It is also possible in this hook function to redirect to another file. If the upper application requires memory or any specific resource to process the request, it should be allocated within this hook function.

Prototype#

CPU_BOOLEAN  HTTPs_ReqHook(const  HTTPs_INSTANCE  *p_instance,
                                  HTTPs_CONN      *p_conn,
                           const  void            *p_hook_cfg);

Arguments#

p_instance

Pointer to the instance structure (read only).

p_conn

Pointer to the connection structure.

p_hook_cfg

Pointer to hook application data.

Return Values#

  • DEF_YES,

If the client is authorized to access the requested resource

  • DEF_NO,

otherwise, Status code returned will be set automatically to unauthorized

Required Configuration#

See section Hook Configuration .

Notes / Warnings#

  • The instance structure is for read-only. It must not be modified at any point in this hook function.

  • The following connection attributes can be accessed to analyze the connection (see section Control Structures for further details on each parameters):

    • ClientAddr

    • Method

    • PathPtr

    • ReqHdrCtr

    • ReqHdrFirstPtr

  • In this hook function, only the under-mentioned connection parameters are allowed to be modified (see section Control Structures for further details on each parameters):

    • StatusCode

    • PathPtr

    • FilePtr

    • FileLen

    • BodyDataType

    • ConnDataPtr

Example Template#

Listing below is shown to demonstrate the HTTP Server module capabilities. That code simply read all header field and print the cookie header field value.

Listing - Request Hook Example Code#
static  CPU_BOOLEAN  HTTPs_ReqHook(const  HTTPs_INSTANCE  *p_instance,
                                          HTTPs_CONN      *p_conn,
                                   const  void            *p_hook_cfg)
{
#if (HTTPs_CFG_HDR_EN == DEF_ENABLED)
  HTTPs_HDR_BLK  *p_req_hdr_blk;
#endif

#if (HTTPs_CFG_HDR_EN == DEF_ENABLED)
  p_req_hdr_blk = p_conn->ReqHdrFirstPtr;

  while (p_req_hdr_blk != DEF_NULL) {
    switch (p_req_hdr_blk->HdrField) {
      case HTTP_HDR_FIELD_COOKIE:
         printf("cookie received: %s\n", (CPU_CHAR *)p_req_hdr_blk->ValPtr);
         break;

      default:
         break;
    }
    p_req_hdr_blk = p_req_hdr_blk->HdrBlkNextPtr;
  }
#endif

  return (DEF_OK);
}

On Request Body Received Hook#

This hook function, if defined, is called by the HTTP Server stack when data is received in the HTTP request body. It allows the upper application to parse the data received to save it or take action on it. The hook function will NOT be called when the HTTP server receives a POST request containing a form. In that case, the server core will take care of parsing the body and saving the data into CGI field blocks. See section HTTP Server Hook Functions for the diagram showing at what moment the hook is called in the HTTP transaction processing.

Prototype#

CPU_BOOLEAN  HTTPs_ReqBodyRxHook (const  HTTPs_INSTANCE  *p_instance,
                                         HTTPs_CONN      *p_conn,
                                  const  void            *p_hook_cfg,
                                         void            *p_buf,
                                  const  CPU_SIZE_T       buf_size,
                                         CPU_SIZE_T      *p_buf_size_used);

Arguments#

p_instance

Pointer to the instance structure (read only).

p_conn

Pointer to the connection structure (read only).

p_hook_cfg

Pointer to hook application data.

p_buf

Pointer to the data buffer.

buf_size

Size of the data received available inside the buffer.

p_buf_size_used

Pointer to the variable that will received the length of the data consumed by the app.

Return Value#

  • DEF_YES

If the data have been consumed by the application.

  • DEF_NO

Otherwise.

Required Configuration#

See section Hook Configuration .

Notes / Warnings#

  • The instance structure is read-only. It must not be modified.

  • Connection structure must not be modified by this function since the response is mostly ready to be transmitted.

Example Template#

The listing below is shown to demonstrate the HTTP Server module capabilities. That code simply copies the data received in an application buffer.

Listing - Add Header field hook function example code#
#define  APP_BUF_LEN    4096

CPU_CHAR  AppBuf[APP_BUF_LEN];

static  CPU_BOOLEAN  HTTPs_ReqBodyRxHook (const  HTTPs_INSTANCE  *p_instance,
                                                 HTTPs_CONN      *p_conn,
                                          const  void            *p_hook_cfg,
                         void            *p_buf,
                                          const  CPU_SIZE_T       buf_size,
                                                 CPU_SIZE_T      *p_buf_size_used)
{
  static  CPU_INT16U  buf_ix = 0;
            CPU_INT16U  len;

  len = DEF_MIN(buf_size, (APP_BUF_LEN - buf_ix));
  if (len == 0) {
    return (DEF_NO);
  }

  Mem_Copy(&AppBuf[buf_ix], p_buf, len);

   *p_buf_size_used = len;
    buf_ix         += len;

  return (DEF_YES);
}

Request Ready Signal#

This hook function, if defined, is called by the HTTP Server after an HTTP request has been completely received as shown in the figure HTTP Server Hook Functions . It allows the upper application to do whatever it needs with data received in the request body. The hook function SHOULD NOT be blocking and SHOULD return quickly. A time consuming function will block the processing of the other connections and reduce the HTTP server performance. In case the request processing is time consuming, the Poll hook function SHOULD be enabled to allow the server to periodically verify if the upper application has finished the request processing. If the hook is not required by the upper application, it can be set as DEF_NULL and no function will be called.

Prototype#

CPU_BOOLEAN  HTTPs_ReqRdySignalHook (const  HTTPs_INSTANCE  *p_instance,
                                            HTTPs_CONN      *p_conn,
                                     const  void            *p_hook_cfg,
                                     const  HTTPs_KEY_VAL   *p_data);

Arguments#

p_instance

Pointer to the instance structure (read only).

p_conn

Pointer to the connection structure.

p_hook_cfg

Pointer to hook application data.

p_data

  • Pointer to the first control key value pair, if any form was received.

  • DEF_NULL, otherwise.

Return Values#

  • DEF_YES

If the response can be sent.

  • DEF_NO

if the response cannot be sent after this call and Poll function MUST be called before sending the response

Required Configuration#

See section Hook Configuration .

Notes / Warnings#

  • The instance structure is read-only. It must not be modified.

  • The following connection attributes can be accessed to analyze the connection (see HTTPs_CONN in Control Structures for further details on each parameters):

    • ClientAddr

    • Method

    • PathPtr

    • ReqHdrCtr

    • ReqHdrFirstPtr

    • ConnDataPtr

  • In this hook function, only the under-mentioned connection parameters are allowed to be modified (see HTTPs_CONN in Control Structures for further details on each parameters):

    • StatusCode

    • PathPtr

    • FilePtr

    • FileLen

    • BodyDataType

  • If the request data take a while to be processed:

    • The processing should be done in a separate task and not in this callback function to avoid blocking other connections.

    • The poll callback function should be used to allow the connection to poll periodically the upper application and verify if the request processing has been completed.

      Note that The ConnDataPtr attribute inside de HTTPs_CONN structure can be used to store a semaphore pointer related or anything else that can help to determine the completion of the request processing.

Example Template#

The listing below is shown to demonstrate the HTTP Server module capabilities. That code analyses each key value pair in the list and try to find control name which is linked to led blinking functionality and change the document returned to display the led state using a data in memory as well.

Listing - CGI post hook function example code#
static  CPU_BOOLEAN  HTTPs_ReqRdySignalHook (const  HTTPs_INSTANCE   *p_instance,
                                                    HTTPs_CONN       *p_conn,
                                              const  void            *p_hook_cfg,
                                              const  HTTPs_KEY_VAL   *p_data)
{
          HTTPs_KEY_VAL   *p_key_val;
  static  CPU_CHAR         buf[4];
          CPU_INT16S       str_cmp;
          CPU_SIZE_T       str_len;
  static  CPU_BOOLEAN      led1_val;
  static  CPU_BOOLEAN      led2_val;
          CPU_BOOLEAN      led_val;
          RTOS_ERR         err;

    p_key_val = (HTTPs_KEY_VAL *)p_data;

    while (p_key_val != DEF_NULL) {                                                           (1)

    printf("Ctrl Name = %s, Value = %s\n\r",
                p_key_val->KeyPtr,
                p_key_val->ValPtr);

    if (p_key_val->DataType == HTTPs_KEY_VAL_TYPE_PAIR) {                                 (2)

      str_cmp = Str_Cmp_N(p_key_val->KeyPtr, "LED", p_key_val->KeyLen);                 (3)

      if (str_cmp == 0) {

        str_cmp = Str_Cmp_N(p_key_val->ValPtr, "LED1", p_key_val->ValLen);            (4)

        if (str_cmp == 0) {
                  led1_val = !led1_val;
                  led_val  = led1_val;
              } else {
                   str_cmp = Str_Cmp_N(p_key_val->ValPtr, "LED2", p_key_val->ValLen);                          if (str_cmp == 0) {
                      led2_val = !led2_val;
                      led_val  = led2_val;
                  }
        }

        if (led_val == DEF_ON) {                                                      (6)
                  str_len          = Str_Len("ON");
                   Str_Copy(&buf[0], "ON");
              } else {
                  str_len          = Str_Len("OFF");
                  Str_Copy(&buf[0], "OFF");
              }

                HTTPs_RespBodySetParamStaticData(p_instance,                                  (7)
                                                 p_conn,
                                                  HTTP_CONTENT_TYPE_PLAIN,
                                                &buf[0],
                                                 str_len,
                                                  DEF_NO,
                                                &err);
    }

    } else if (p_key_val->DataType == HTTPs_KEY_VAL_TYPE_FILE) {                          (8)

            HTTPs_RespBodySetParamFile(p_instance,                                            (9)
                                       p_conn,
                                       p_key_val->ValPtr,
                                        HTTP_CONTENT_TYPE_UNKNOWN,
                                        DEF_YES,
                                      &err);
       }

      p_key_val = p_key_val->DataNextPtr;

  }

  return (DEF_NO);
}
  1. Analyze each key value pair into the list

  2. Make sure the key value pair item is a control key and not a file.

  3. If the control name starts with the key word ‘LED’ than a led should be toggled.

  4. If the value contains ‘LED1’ than the first led should be toggled.

  5. Else if the value contains ‘LED2’ than the second led should be toggled.

  6. Update memory data to transmit based on the led state.

  7. Set the data to send in the response body.

  8. If the key value pair is for a file uploaded.

  9. Change the file to be transmitted equal to the file just received.

Request Ready Poll#

The Poll hook function SHOULD be enable in case the request processing require lots of time. It allows the HTTP server to periodically poll the upper application and verify if the request processing has finished, as shown in the figure HTTP Server Hook Functions . If the Poll feature is not required, this field SHOULD be set as DEF_NULL.

Prototype#

CPU_BOOLEAN  HTTPs_ReqRdyPollHook (const  HTTPs_INSTANCE  *p_instance,
                                          HTTPs_CONN      *p_conn,
                                   const  void            *p_hook_cfg);

Arguments#

p_instance

Pointer to the instance structure (read only).

p_conn

Pointer to the connection structure.

p_hook_cfg

Pointer to hook application data.

Return Values#

  • DEF_YES

If the request processing is completed and the response can be sent.

  • DEF_NO

If the request processing is not completed and the Poll function must be called again to know the end of processing.

Required Configuration#

See section Hook Configuration .

Notes / Warnings#

  • The instance structure is for read-only. It must not be modified.

  • The following connection attributes can be accessed to analyze the connection (see HTTPs_CONN in Control Structures for further details on each parameters):

    • ClientAddr

    • Method

    • PathPtr

    • ReqHdrCtr

    • ReqHdrFirstPtr

    • ConnDataPtr

  • In this hook function, only the under-mentioned connection parameters are allowed to be modified (see HTTPs_CONN in Control Structures for further details on each parameters):

    • StatusCode

    • PathPtr

    • FilePtr

    • FileLen

    • BodyDataType

  • If request data take a while to be processed:

The poll callback function should be used to allow the HTTP server core to poll periodically the upper application and verify if the request data processing has been completed. Note that The ConnDataPtr attribute inside the HTTPs_CONN structure can be used to store a semaphore pointer related to the completion of the request processing.

Example Template#

The listing below demonstrates the HTTP Server module capabilities. That code just returns the state of the request processing state, assuming it’s possible to post only one processing at a time.

Listing - CGI poll hook function example code#
static  CPU_BOOLEAN  req_processing_state = DEF_YES;

static  CPU_BOOLEAN  HTTPs_ReqRdyPollHook (const  HTTPs_INSTANCE  *p_instance,
                                                  HTTPs_CONN      *p_conn,
                                           const  void            *p_hook_cfg)
{
   return (req_processing_state)
}

Add Response Header Field#

This hook function, if defined, is called by the HTTP Server module before starting to transmit the response message as shown on HTTP Server Hook Functions . It allows the upper application to add header field to the response by calling a specific API function with header field type and value.

Prototype#

CPU_BOOLEAN  HTTPs_RespHdrTxHook (const  HTTPs_INSTANCE  *p_instance,
                                         HTTPs_CONN      *p_conn,
                                  const  void            *p_hook_cfg);

Arguments#

p_instance

Pointer to the instance structure (read only).

p_conn

Pointer to the connection structure (read only).

p_hook_cfg

Pointer to hook application data.

Return Value#

  • DEF_YES

If all header fields are added without error.

  • DEF_NO

otherwise.

Required Configuration#

HTTPs_CFG_HDR_EN must be enabled in the http_server_cfg.h file (see section Module Configuration ).

The header feature must also be enabled in the Instance configuration (see section Instance Configuration ).

See section Hook Configuration .

Notes / Warnings#

  • The instance structure is for read-only. It must not be modified.

  • Connection structure must not be modified by this function since the response is mostly ready to be transmitted.

Example Template#

The listing below is shown to demonstrate the HTTP Server module capabilities. That code simply add two header fields to a response message for an HTML document.

Listing - Add Header field hook function example code#
static  CPU_BOOLEAN  HTTPs_RespHdrTxHook (const  HTTPs_INSTANCE  *p_instance,
                                                 HTTPs_CONN      *p_conn,
                                          const  void            *p_hook_cfg)
{
#if (HTTPs_CFG_HDR_EN == DEF_ENABLED)
           HTTPs_HDR_BLK  *p_resp_hdr_blk;
  const  HTTPs_CFG      *p_cfg;
           CPU_CHAR       *str_data;
           CPU_SIZE_T      str_len;
           RTOS_ERR        http_err;

  p_cfg = p_instance->CfgPtr;

    switch (p_conn->StatusCode) {
      case HTTPs_STATUS_OK:                                                              (1)
             if (p_conn->FileContentType == HTTPs_CONTENT_TYPE_HTML) {                     (2)
                 p_resp_hdr_blk = HTTPs_RespHdrGet(p_instance,                             (3)
                                                   p_conn,
                                                   HTTPs_HDR_FIELD_SET_COOKIE,
                                                   HTTPs_HDR_VAL_TYPE_STR_DYN,
                                                  &http_err);
                 if (p_resp_hdr_blk == DEF_NULL) {
                     return(DEF_FAIL);
                 }

         str_data = "user=micrium";
                 str_len = Str_Len_N(str_data, p_cfg->RespHdrStrLenMax);
                 Str_Copy_N(p_resp_hdr_blk->ValPtr,                                        (4)
                            str_data,
                            str_len);

                 p_resp_hdr_blk->ValLen = str_len;

                 p_resp_hdr_blk = HTTPs_RespHdrGet(p_instance,                             (5)
                                                   p_conn,
                                                   HTTPs_HDR_FIELD_SERVER,
                                                   HTTPs_HDR_VAL_TYPE_STR_DYN,
                                                  &http_err);
                 if (p_resp_hdr_blk == DEF_NULL) {
                     return(DEF_FAIL);
                 }

                 str_data = "uC-HTTPs V2.00.00";
                 str_len = Str_Len_N(str_data, p_cfg->RespHdrStrLenMax);                   (6)
                 Str_Copy_N(p_resp_hdr_blk->ValPtr,
                            str_data,
                            str_len);

                 p_resp_hdr_blk->ValLen = str_len;
             }
             break;

         default:
             break;
  }
#endif

  return (DEF_YES);
}
  1. Ensure that we don’t add header field to a response with an error

  2. Make sure to add header field only on HTML document.

  3. Acquire and add a first header field block of type ‘Cookie’ and with a string value type to the connection

  4. Set the value string value (cookie content) and the string length.

  5. Acquire and add a second header field block of type ‘Server’ and with a string value type to the connection

  6. Set the value string value (server name) and the string length.

Get Token Value#

This hook function, if defined, is called by the HTTP Server when a token is found into a plain document such as HTML during the response construct process as shown in the figure HTTP Server Hook Functions . It allows the upper application to populate some part of a document dynamically.

Prototype#

CPU_BOOLEAN  HTTPs_RespTokenValGetHook(const  HTTPs_INSTANCE  *p_instance,
                                              HTTPs_CONN      *p_conn,
`                     const  void            *p_hook_cfg,`
                     const  CPU_CHAR        *p_token,
                                              CPU_INT16U       token_len,
                                              CPU_CHAR        *p_val,
                                              CPU_INT16U       val_len_max);

Arguments#

p_instance

Pointer to the instance structure (read only).

p_conn

Pointer to the connection structure.

p_hook_cfg

Pointer to hook application data.

p_token

Pointer to the string that contains the token name.

token_len

Length of the token.

p_val

Pointer to string where to copy the token substitution value.

val_len_max

Maximum string value length.

Return Values#

  • DEF_OK

If token value copied successfully.

  • DEF_FAIL

Otherwise (see Notes).

Required Configuration#

See Token Replacement Compile-time Configuration and Token Replacement Run-time Configuration .

Notes / Warnings#

  • The instance structure is for read-only. It must not be modified.

  • Connection structure must not be modified by this function since the response transmission is started.

  • If the token replacement failed, the token will be replaced by a line of tilde (~) of length equal to val_len_max.

Example Template#

The listing below demonstrates the HTTP Server module capabilities. That code just look if the token is equal to "TEXT_STRING" and replace it by "TEXT" else it returns an error and let the server replace the token by the default value.

Listing - CGI poll hook function example code#
static  CPU_BOOLEAN  HTTPs_RespTokenValGetHook (const  HTTPs_INSTANCE  *p_instance,
                                                       HTTPs_CONN      *p_conn,
                        const  void            *p_hook_cfg,
                        const  CPU_CHAR        *p_token,
                                                       CPU_INT16U       token_len,
                                                       CPU_CHAR        *p_val,
                                                       CPU_INT16U       val_len_max)
{
  if (Str_Cmp_N(p_token, "TEXT_STRING", 11) == 0) {
        Str_Copy_N(p_val, "Text", val_len_max);
        return (DEF_OK);
  }

  return (DEF_FAIL);
}

On Response Chunk Hook#

To allow the upper application to transmit data with the Chunked Transfer Encoding, this hook function is available. If defined, it will be called at the moment of the Response body transfer (as shown in section HTTP Server Hook Functions ), and it will be called until the application has transfer all its data. If the hook is not required by the upper application, it can be set as DEF_NULL and no function will be called.

Furthermore, for the hook to be called, the RespBodyDataType parameter of HTTPs_CONN must be set to HTTPs_BODY_DATA_TYPE_STATIC_DATA and the DataPtr parameter must be null. See section Response Body Data for more details on how to send application data in chunk.

Prototype#

CPU_BOOLEAN  HTTPs_RespChunkDataGetHook(const  HTTPs_INSTANCE  *p_instance,
                                               HTTPs_CONN      *p_conn,
                                        const  void            *p_hook_cfg,
                                               void            *p_buf,
                                               CPU_SIZE_T       buf_len_max,
                                               CPU_SIZE_T      *p_tx_len);

Arguments#

p_instance

Pointer to the instance structure (read only).

p_conn

Pointer to the connection structure.

p_hook_cfg

Pointer to hook application data.

p_buf

Pointer to the buffer to fill.

buf_len_max

Maximum length the buffer can contain.

p_tx_len

Pointer to variable that will received the length written in the buffer.

Return Values#

  • DEF_YES

if there is no more data to send.

  • DEF_NO

Otherwise.

Required Configuration#

See section Hook Configuration .

Notes / Warnings#

  • The instance structure is for read-only. It must not be modified.

  • Connection structure must not be modified by this function. All the parameters to change are already passed as arguments.

Example Template#

The listing below demonstrates the HTTP Server module capabilities.

Listing - CGI poll hook function example code#
static  CPU_BOOLEAN  HTTPs_RespChunkDataGetHook (const  HTTPs_INSTANCE  *p_instance,
                                                        HTTPs_CONN      *p_conn,
                         const  void            *p_hook_cfg,
                                void            *p_buf,
                                                        CPU_SIZE_T       buf_len_max,
                                                        CPU_SIZE_T      *p_tx_len)
{
#if (HTTPs_CFG_FORM_EN == DEF_ENABLED)
    const  HTTPs_CFG      *p_cfg = p_instance->CfgPtr;
           HTTPs_KEY_VAL  *p_key_val;
           CPU_INT16S      str_cmp;

    str_cmp = Str_Cmp_N(p_conn->PathPtr, FORM_SUBMIT_URL, p_conn->PathLenMax);
    if (str_cmp == 0) {
                                                                /* Construct JSON for user                              */
        Str_Copy(p_buf, "{\"user\": {\"first name\": \"");      /* Add First Name field.                                */
        p_key_val = p_conn->FormDataListPtr;
        while (p_key_val != DEF_NULL) {
            str_cmp = Str_Cmp_N(p_key_val->KeyPtr, "firstname", p_cfg->FormCfgPtr->KeyLenMax);
            if (str_cmp == 0) {
                Str_Cat_N(p_buf, p_key_val->ValPtr, p_key_val->ValLen);
                break;
            }
            p_key_val = p_key_val->NextPtr;
        }
        Str_Cat(p_buf, "\", \"last name\":\"");                 /* Add Last Name field.                                 */
        p_key_val = p_conn->FormDataListPtr;
        while (p_key_val != DEF_NULL) {
            str_cmp = Str_Cmp_N(p_key_val->KeyPtr, "lastname", p_cfg->FormCfgPtr->KeyLenMax);
            if (str_cmp == 0) {
                Str_Cat_N(p_buf, p_key_val->ValPtr, p_key_val->ValLen);
                break;
            }
            p_key_val = p_key_val->NextPtr;
        }
        Str_Cat(p_buf, "\"}}");
    }
   *p_tx_len = Str_Len_N(p_buf, p_cfg->BufLen);
#else
     CPU_SW_EXCEPTION(;);
#endif
    return (DEF_YES);
}

Get Error Document#

This hook function, if defined, is called by the HTTP Server instance every time the response status code has been changed to a value that is associated with an error to allow the upper application to send the appropriate error page as shown in the figure HTTP Server Hook Functions . The change could be the result of the request processing in the Connection request hook function or the result of an internal error in the HTTP Server core. This function is intended to set the name of the file which will be sent with the response message. If no file is set, a default status page will be sent including the status code number and the reason phrase.

Prototype#

void  HTTPs_ErrFileGetHook (const  void                   *p_hook_cfg,
                                   HTTP_STATUS_CODE        status_code,
                                   CPU_CHAR               *p_file_str,
                                   CPU_INT32U              file_len_max,
                                   HTTPs_BODY_DATA_TYPE   *p_file_type,
                                   HTTP_CONTENT_TYPE      *p_content_type,
                                   void                  **p_data,
                                   CPU_INT32U             *p_data_len);

Arguments#

p_hook_cfg

Pointer to hook application data.

status_code

Status code number of the response message.

p_file_str

Pointer to the string buffer where the filename string must be copied.

file_len_max

Maximum string length of the filename.

p_file_type

Pointer to the variable holding the file type, can be modified by this function when data must be transmitted instead of a file:

  • HTTPs_BODY_DATA_TYPE_FILE

  • HTTPs_BODY_DATA_TYPE_STATIC_DATA

  • HTTPs_BODY_DATA_TYPE_NONE

p_content_type

Content type of the body. If the data is a File, the content type doesn't need to be set. It will be set according to the file extension. If the data is Static Data, the parameter MUST be set.

p_data

  • Pointer to the data memory block,

  • Must set if file type is configured as HTTPs_BODY_DATA_TYPE_STATIC_DATA.

  • DEF_NULL, otherwise.

p_data_len

  • Pointer to variable holding the length of the data,

  • Must set if file type is configured as HTTPs_FILE_TYPE_STATIC_DATA.

  • DEF_NULL, otherwise

Return Values#

None.

Required Configuration#

See section Hook Configuration .

Notes / Warnings#

If the configured file doesn't exist the instance will transmit the default web page instead, defined by “HTTPs_CFG_HTML_DFLT_ERR_PAGE” in http_server_cfg.h.

Example Template#

The listing below demonstrates the HTTP Server module capabilities. That code simply use a file for 404 error and the default document for any other error.

Listing - Connection get error document hook function example code#
#define  HTTPs_CFG_INSTANCE_STR_FILE_ERR_404              "404.html"

static  void  HTTPs_ErrFileGetHookt (const  void                   *p_hook_cfg,
                                            HTTPs_STATUS_CODE       status_code,
                                            CPU_CHAR               *p_file_str,
                                            CPU_INT32U              file_len_max,
                                            HTTPs_BODY_DATA_TYPE   *p_file_type,
                                            HTTP_CONTENT_TYPE      *p_content_type,
                                            void                  **p_data,
                                            CPU_INT32U             *p_data_len)
{
  switch (status_code) {
      case HTTP_STATUS_NOT_FOUND:
             Str_Copy_N(p_file_str, HTTPs_CFG_INSTANCE_STR_FILE_ERR_404, file_len_max);
            *p_file_type = HTTPs_BODY_DATA_TYPE_FILE;
             return;

        default:
            *p_data         = HTTPs_CFG_HTML_DFLT_ERR_PAGE;
            *p_data_len     = HTTPs_HTML_DLFT_ERR_LEN;
            *p_file_type    = HTTPs_BODY_DATA_TYPE_STATIC_DATA;
            *p_content_type = HTTP_CONTENT_TYPE_HTML;
             return;
  }

}

Connection Error#

This hook function, if defined, is called every time an error occurred when processing the request or the method to notify the upper application and change the default behavior as shown shown in the figure HTTP Server Hook Functions . This function can analyses the error and change the status code and the file to return.

Prototype#

void  HTTPs_ErrHook (const  HTTPs_INSTANCE  *p_instance,
                            HTTPs_CONN      *p_conn,
                     const  void            *p_hook_cfg,
                            HTTPs_ERR        err);

Arguments#

p_instance

Pointer to the instance structure (read only).

p_conn

Pointer to the connection structure.

p_hook_cfg

Pointer to hook application data.

err

Error code .

Return Values#

None.

Required Configuration#

See section Hook Configuration .

Notes / Warnings#

  • The instance structure is for read-only. It must not be modified at any point in this hook function.

  • The following connection attributes can be accessed to analyze the connection (see HTTPs_CONN in Control Structures for further details on each parameters):

    • ClientAddr

    • Method

    • PathPtr

    • HdrCtr

    • HdrListPtr

  • In this hook function, only the under-mentioned connection parameters are allowed to be modified (see HTTPs_CONN in Control Structures for further details on each parameters):

    • StatusCode

    • PathPtr

    • DataPtr

    • DataLen

    • BodyDataType

    • ConnDataPtr

Example Template#

The listing below demonstrates the HTTP Server module capabilities. That code simply read error and print file not found errors.

Listing - Error Hook Example Code#
static  void  HTTPs_ErrHook (const  HTTPs_INSTANCE  *p_instance,
                                    HTTPs_CONN      *p_conn,
                             const  void            *p_hook_cfg,
                        HTTPs_ERR        err)
{
  switch (err) {
    case HTTPs_ERR_FILE_404_NOT_FOUND:
       printf("Error 404 File not found occurred.\n");
             return;

         default:
             break;
  }
}

On Transaction Complete Hook#

This hook function, if defined, is called every time a HTTP transaction is completed to notify the upper application to release resource allocated related to a transaction, as shown in the figure HTTP Server Hook Functions .

Prototype#

void  HTTPs_TransCompleteHook (const  HTTPs_INSTANCE  *p_instance,
                                      HTTPs_CONN      *p_conn,
                               const  void            *p_hook_cfg);

Arguments#

p_instance

Pointer to the instance structure (read only).

p_conn

Pointer to the connection structure.

p_hook_cfg

Pointer to hook application data.

Return Values#

None.

Required Configuration#

See section Hook Configuration .

Notes / Warnings#

  • The instance structure is for read-only. It must not be modified.

  • The connection structure is read-only since the connection will be freed after this call.

ConnDataPtr parameter should be used to store the location of the data allocated.

Example Template#

The listing below is shown to demonstrate the HTTP Server module capabilities. That code simply print that the HTTP transaction is completed. The hook will be usually used to release objects allocated for the duration of an HTTP transaction.

Listing - Transaction Complete Hook Example Code#
static  void  HTTPs_TransCompleteHook (const  HTTPs_INSTANCE  *p_instance,
                                              HTTPs_CONN      *p_conn,
                       const  void            *p_hook_cfg)
{
  printf("HTTP transaction is completed.\n\r");
}

Connection Close#

This hook function, if defined, is called every time a connection is closed to notify the upper application to release resource allocated related to an HTTP connection, as shown in the figure HTTP Server Hook Functions .

Prototype#

void  HTTPs_ConnCloseHook (const  HTTPs_INSTANCE  *p_instance,
                                  HTTPs_CONN      *p_conn,
                           const  void            *p_hook_cfg);

Arguments#

p_instance

Pointer to the instance structure (read only).

p_conn

Pointer to the connection structure.

p_hook_cfg

Pointer to hook application data.

Return Values#

None.

Required Configuration#

See Hook Configuration .

Notes / Warnings#

  • The instance structure is for read-only. It must not be modified.

  • The connection structure is read-only since the connection will be freed after this call.

ConnDataPtr parameter should be used to store the location of the data allocated.

Example Template#

The listing below is shown to demonstrate the HTTP Server module capabilities. That code simply print that the connection is closing.

Listing - Connection Close Hook Example Code#
static  void  HTTPs_ConnCloseHook (const  HTTPs_INSTANCE  *p_instance,
                                          HTTPs_CONN      *p_conn,
                                   const  void            *p_hook_cf)
{
  printf("Connection is closing.\n\r");
}

HTTP Server Add-on API#

This section provides a reference to the HTTP Server add-on modules API.

Auth Module API#

The Authentication add-on requires you to set three hook functions to work properly:

You will also need to use some functions from the Authentication module of Micrium OS Common to create users and right levels.

Get Required Rights Hook#

This hook will be called by the Authentication Layer of the Control Layer when a request is received to check with the upper application what rights are associated with this request.

Prototype#
AUTH_RIGHT  HTTPsAuth_GetRequiredRightsHook (const  HTTPs_INSTANCE  *p_instance,
                                             const  HTTPs_CONN      *p_conn);
Arguments#

p_instance

Pointer to the instance structure (read only).

p_conn

Pointer to the connection structure (read only).

Return Values#

The authorization right level for this HTTP transaction.

Required Configuration#

None.

Notes / Warnings#

None.

Example Template#
Listing - Get Required Rights Hook Example#
#define  HTTP_USER_ACCESS  AUTH_RIGHT_2

/*
*********************************************************************************************************
*                                    AppGlobal_Auth_GetRequiredRightsHook()
*
* Description : Returns the rights required to fulfill the needs of a given request.
*
* Argument(s) : p_instance  Pointer to the HTTP server instance object.
*
*               p_conn      Pointer to the HTTP connection object.
*
* Return(s)   : returns the authorization right level for this example application.
*
* Note(s)     : none.
*********************************************************************************************************
*/

AUTH_RIGHT  AppGlobal_Auth_GetRequiredRightsHook (const  HTTPs_INSTANCE  *p_instance,
                                                  const  HTTPs_CONN      *p_conn)
{
    return (HTTP_USER_ACCESS);
}

Login Hook#

This hook will be called by the Application Layer of the Control Layer to found requests related to the log in process, e.g., the GET requests for the resources of the log in page (html, css, images) and the POST request with the log in form.

This hook functions are called on two occasions:

  • When the URL and headers of the request were received and parse by the server (state HTTPs_AUTH_STATE_REQ_URL)

  • When the request body was received and parse (state HTTPs_AUTH_STATE_REQ_COMPLETE)

Prototype#
CPU_BOOLEAN  AppGlobal_Auth_ParseLoginHook (const  HTTPs_INSTANCE     *p_instance,
                                            const  HTTPs_CONN         *p_conn,
                                                   HTTPs_AUTH_STATE    state,
                                                   HTTPs_AUTH_RESULT  *p_result);
Arguments#

p_instance

Pointer to the instance structure (read only).

p_conn

Pointer to the connection structure (read only).

state

State of the Authentication module:

  • HTTPs_AUTH_STATE_REQ_URL

  • HTTPs_AUTH_STATE_REQ_COMPLETE

p_result

Pointer to the authentication result structure that the hook needs to fill.

Return Values#
  • DEF_YES, if the request is the POST with the log in information in a form.

  • DEF_NO, otherwise.

Required Configuration#

None.

Notes / Warnings#

None.

Example Template#
Listing - Login Hook Example#
/*
*********************************************************************************************************
*                                     AppGlobal_Auth_ParseLoginHook()
*
* Description : (1) Check all the HTTP requests received to see if they are related to resources of the login page.
*                   (a) Check if the POST login is received.
*                   (b) For each request set the redirect paths on no, invalid & valid credentials.
*                   (c) Parse the form fields received in the body for the user and password.
*
*
* Argument(s) : p_instance  Pointer to the HTTP server instance object.
*
*               p_conn      Pointer to the HTTP connection object.
*
*               state       State of the Authentication module:
*                               HTTPs_AUTH_STATE_REQ_URL:      The url and the headers were received and parse.
*                               HTTPs_AUTH_STATE_REQ_COMPLETE: All the request (url + headers + body) was received and parse.
*
*               p_result    Pointer to the authentication result structure to fill.
*
* Return(s)   : DEF_YES, if the request is the POST login.
*               DEF_NO,  otherwise.
*
* Note(s)     : (2) This hook will be called twice for a request processed by the Authentication module:
*                   (a) When the Start line of the request (with the url) and the headers have been
*                       received and parse -> HTTPs_AUTH_STATE_REQ_URL state.
*                   (b) When all the request has been completely received and parse including the body
*                       -> HTTPs_AUTH_STATE_REQ_COMPLETE state.
*
*               (3) for each request received the redirect paths is set as follow:
*                   (a) RedirectPath_OnValidCred    INDEX_PAGE_URL
*                   (b) RedirectPath_OnInvalidCred  LOGIN_PAGE_URL
*                   (c) RedirectPath_OnNoCred
*                       (1) if the path is an unprotected path, let it go. (DEF_NULL) (i.e., the logo)
*                       (2) otherwise               LOGIN_PAGE_URL
*********************************************************************************************************
*/
CPU_BOOLEAN  AppGlobal_Auth_ParseLoginHook (const  HTTPs_INSTANCE     *p_instance,
                                            const  HTTPs_CONN         *p_conn,
                                                   HTTPs_AUTH_STATE    state,
                                                   HTTPs_AUTH_RESULT  *p_result)
{
    CPU_INT16S      cmp_val;
    CPU_BOOLEAN     is_login = DEF_NO;
#if (HTTPs_CFG_FORM_EN == DEF_ENABLED)
    HTTPs_KEY_VAL  *p_current;
    CPU_INT16S      cmp_val_username;
    CPU_INT16S      cmp_val_password;
#endif
    p_result->UsernamePtr = DEF_NULL;
    p_result->PasswordPtr = DEF_NULL;
                                                                /* Set redirect paths for each requests.                */
    p_result->RedirectPathOnInvalidCredPtr = LOGIN_PAGE_URL;
    p_result->RedirectPathOnValidCredPtr   = INDEX_PAGE_URL;
    switch (state) {
                                                                 /* --------------- REQUEST URL RECEIVED --------------- */
        case HTTPs_AUTH_STATE_REQ_URL:
                                                                /* Set redirect paths for each requests.                */
             cmp_val = Str_Cmp(p_conn->PathPtr, LOGIN_PAGE_URL);
             if (cmp_val != 0) {
                 cmp_val = Str_Cmp(p_conn->PathPtr, MICRIUM_LOGO_URL);
                 if (cmp_val != 0) {
                     cmp_val = Str_Cmp(p_conn->PathPtr, MICRIUM_CSS_URL);
                 }
             }
             p_result->RedirectPathOnNoCredPtr = (cmp_val == 0) ? DEF_NULL : LOGIN_PAGE_URL;
                                                                /* Check if POST login received.                        */
             cmp_val = Str_Cmp(p_conn->PathPtr, LOGIN_PAGE_CMD);
             if (cmp_val == 0) {
                 is_login = DEF_YES;
             }
             break;
                                                                 /* -------------- REQUEST BODY RECEIVED --------------- */
        case HTTPs_AUTH_STATE_REQ_COMPLETE:
#if (HTTPs_CFG_FORM_EN == DEF_ENABLED)
                                                                /* Parse form fields received for user/password.        */
             p_current = p_conn->FormDataListPtr;
             while ((p_current              != DEF_NULL)  &&
                    ((p_result->UsernamePtr == DEF_NULL)  ||
                     (p_result->PasswordPtr == DEF_NULL))) {
                 if (p_current->DataType == HTTPs_KEY_VAL_TYPE_PAIR) {
                     cmp_val_username = Str_CmpIgnoreCase_N(p_current->KeyPtr,
                                                             FORM_USERNAME_FIELD_NAME,
                                                            p_current->KeyLen);
                     cmp_val_password = Str_CmpIgnoreCase_N(p_current->KeyPtr,
                                                             FORM_PASSWORD_FIELD_NAME,
                                                            p_current->KeyLen);
                     if (cmp_val_username == 0) {
                         p_result->UsernamePtr = p_current->ValPtr;
                         is_login = DEF_YES;
                     } else if (cmp_val_password == 0) {
                         p_result->PasswordPtr = p_current->ValPtr;
                     }
                 }
                 p_current = p_current->NextPtr;
             }
#endif
             break;
        default:
             break;
    }
    return (is_login);
}

Logout Hook#

This hook will be called by the Application Layer of the Control Layer to find out if the request received is a log out request. Depending on the implementation of the this hook, the log out accepted can be a GET or a POST request.

This hook functions will be called on two occasions:

  • When the URL and headers of the request were received and parse by the server (state HTTPs_AUTH_STATE_REQ_URL)

  • When the request body was received and parse (state HTTPs_AUTH_STATE_REQ_COMPLETE)

Prototype#
CPU_BOOLEAN  AppGlobal_Auth_ParseLogoutHook (const  HTTPs_INSTANCE     *p_instance,
                                             const  HTTPs_CONN         *p_conn,
                                                    HTTPs_AUTH_STATE    state);
Arguments#

p_instance

Pointer to the instance structure (read only).

p_conn

Pointer to the connection structure (read only).

state

State of the Authentication module:

  • HTTPs_AUTH_STATE_REQ_URL

  • HTTPs_AUTH_STATE_REQ_COMPLETE

Return Values#
  • DEF_YES, if the request is the POST with the log out information in a form.

  • DEF_NO, otherwise.

Required Configuration#

None.

Notes / Warnings#

None.

Example Template#
Listing - Logout Hook Example#
/*
*********************************************************************************************************
*                                     AppGlobal_Auth_ParseLogoutHook()
*
* Description : Parse requests received for logout URL and form data logout info.
*
* Argument(s) : p_instance  Pointer to HTTPs instance object.
*
*               p_conn      Pointer to HTTPs connection object.
*
*               state       State of the Authentication module:
*                               HTTPs_AUTH_STATE_REQ_URL:      The URL and the headers were received and parse.
*                               HTTPs_AUTH_STATE_REQ_COMPLETE: All the request (URL + headers + body) was received and parse.
*
* Return(s)   : DEF_YES, if Logout received.
*               DEF_NO,  otherwise.
*
* Note(s)     : (1) This hook will be called twice for a request processed by the Authentication module:
*                   (a) When the Start line of the request (with the URL) and the headers have been
*                       received and parse -> HTTPs_AUTH_STATE_REQ_URL state.
*                   (b) When all the request has been completely received and parse including the body
*                       -> HTTPs_AUTH_STATE_REQ_COMPLETE state.
*********************************************************************************************************
*/
CPU_BOOLEAN  AppGlobal_Auth_ParseLogoutHook (const  HTTPs_INSTANCE    *p_instance,
                                             const  HTTPs_CONN        *p_conn,
                                                    HTTPs_AUTH_STATE   state)
{
    CPU_BOOLEAN     is_logout = DEF_NO;
#if (HTTPs_CFG_FORM_EN == DEF_ENABLED)
    HTTPs_KEY_VAL  *p_current;
    CPU_INT16S       cmp_val;
#endif
    switch (state) {
                                                                 /* --------------- REQUEST URL RECEIVED --------------- */
        case HTTPs_AUTH_STATE_REQ_URL:
                                                                /* Check if POST logout received.                       */
             cmp_val = Str_Cmp(p_conn->PathPtr, LOGOUT_PAGE_CMD);
             if (cmp_val == 0) {
                 is_logout = DEF_YES;
             }
             break;
                                                                 /* -------------- REQUEST BODY RECEIVED --------------- */
        case HTTPs_AUTH_STATE_REQ_COMPLETE:
#if (HTTPs_CFG_FORM_EN == DEF_ENABLED)
                                                                /* Parse form fields received for logout.               */
             p_current = p_conn->FormDataListPtr;
             while (p_current != DEF_NULL) {
                 if (p_current->DataType == HTTPs_KEY_VAL_TYPE_PAIR) {
                     cmp_val = Str_CmpIgnoreCase_N(p_current->KeyPtr,
                                                    FORM_LOGOUT_FIELD_NAME,
                                                   p_current->KeyLen);
                     if (cmp_val == 0) {
                         is_logout = DEF_YES;
                         break;
                     }
                 }
                 p_current = p_current->NextPtr;
             }
#endif
             break;
        default:
             break;
    }
    return (is_logout);
}

REST Module API#

The REST add-on module has only one API function to publish, in the global resources list, REST resources created by the application.

This function can only be called after the HTTP server initialization and before the HTTP server start. Also, the HTTPsREST_Init() hook function must be bound to the HTTP server or to the Control layer prior the initialization. Otherwise, the REST memory pools won't be initialized and the resource lists cannot be created.

For each REST resources, a set of hook functions will also need to be defined. For more information refer to section REST module .

HTTPsREST_Publish#

Prototype#
void  HTTPsREST_Publish (const HTTPs_REST_RESOURCE  *p_resource,
                               CPU_INT32U            list_ID,
                               HTTPs_REST_ERR       *p_err);
Arguments#

p_resource

Pointer to the rest resource to publish (read only).

list_ID

Identification of the list to publish on.

p_err

Pointer to variable that will receive the return error code from this function

Return Values#

None.

Required Configuration#

None.

Notes / Warnings#

None.

Example Template#
Listing - REST Publish Resources Example#
/*
*********************************************************************************************************
*                                          AppREST_ResourcesInit()
*
* Description : Initialize the REST application resources.
*
* Argument(s) : none.
*
* Return(s)   : DEF_OK,   if initialization was successful.
*               DEF_FAIL, otherwise.
*
* Note(s)     : none.
*********************************************************************************************************
*/
CPU_BOOLEAN  AppREST_ResourcesInit (void)
{
    RTOS_ERR  err;

    HTTPsREST_Publish(&AppREST_List_Resource, 0, &err);
    if (err.Code != RTOS_ERR_NONE) {
        return (DEF_FAIL);
    }
    HTTPsREST_Publish(&AppREST_User_Resource, 0, &err);
    if (err.Code != RTOS_ERR_NONE) {
        return (DEF_FAIL);
    }
    HTTPsREST_Publish(&AppREST_File_Resource, 0, &err);
    if (err.Code != RTOS_ERR_NONE) {
        return (DEF_FAIL);
    }
    return (DEF_OK);
}