🌐 English

    NetMessage API#

    Oasis network messages are processed through the NetMessage API.

    NetMessage is passed as a parameter to network component interfaces and is used for requests or responses.

    Header File#

    OasisNet.h

    Functions#

    NetMessageRef netMessageCreate ( const NetMessageRef & msg , bool is_request )
    OasisNet.h
    Creates a NetMessage object.
    Parameters
    msg  The reference NetMessage object. When creating a response NetMessage, this is the request message corresponding to the response message.
    is_request  Creates a request message if true, and creates a response message if false.
    Return Value
    Returns a NetMessage object on success, and returns nullptr on failure.
    int32_t netMessageLocalAddressString ( const NetMessageRef & msg , std::string & local_address_string , std::string & local_port_string )
    OasisNet.h
    Returns the address of the local server as a string.
    Parameters
    msg  The NetMessage object.
    local_address_string  OUT The IPv4 address of the local server.
    local_port_string  OUT The port number of the local server.
    Return Value
    • 0: Success
    • -1: Failure
    int32_t netMessageRemoteAddressString ( const NetMessageRef & msg , std::string & remote_address_string , std::string & remote_port_string )
    OasisNet.h
    Returns the address of the remote client connected to the local server as a string.
    Parameters
    msg  The NetMessage object.
    remote_address_string  The IPv4 address of the remote client.
    remote_port_string  The port number of the remote client.
    Return Value
    • 0: Success
    • -1: Failure
    int32_t netMessageGetSocket ( const NetMessageRef & msg )
    OasisNet.h
    The socket handle number connected to the NetMessage object.
    Parameters
    msg  The NetMessage object.
    Return Value
    Returns the socket number. Returns -1 on failure or if not connected.
    int32_t netMessageAbortConnection ( const NetMessageRef & msg )
    OasisNet.h
    Disconnects the server and client connection of the NetMessage object.
    Parameters
    msg  The NetMessage object.
    Return Value
    • 0: Success
    • -1: Failure
    int32_t netMessageGetStatusCodeAndReasonString ( const NetMessageRef & msg , std::string & reason_string )
    OasisNet.h
    Returns the response status code and reason string of HTTP or other text-based protocols from the NetMessage.
    Parameters
    msg  The NetMessage object.
    reason_string  OUT Returns the reason string.
    Return Value
    Returns the status code.
    int32_t netMessageUriGetPath ( const NetMessageRef & msg , std::string & uri_path )
    OasisNet.h
    Obtains the URI path of the NetMessage.
    Parameters
    msg  The NetMessage object.
    uri_path  OUT Returns the URI path.
    Return Value
    • 0: Success
    • -1: Failure
    bool netMessageUriHasQueryParameter ( const NetMessageRef & msg , const char * key )
    OasisNet.h
    Parameters
    msg  The NetMessage object.
    key  The key string to verify.
    Return Value
    • true: The key exists in the query set.
    • false: The key does not exist in the query set.
    int32_t netMessageUriGetQueryParameterValue ( const NetMessageRef & msg , const char * key , std::string & value )
    OasisNet.h
    Obtains the query key value.
    Parameters
    msg  The NetMessage object.
    key  The query key string.
    value  OUT Returns the key value.
    Return Value
    • 0: Success
    • -1: Failure
    int32_t netMessageUriGetQueryParameters ( const NetMessageRef & msg , key_value_map_t & dictionary )
    OasisNet.h
    Obtains the query set as a key-value map.
    Parameters
    msg  The NetMessage object.
    dictionary  OUT Returns the query key-value map.
    Return Value
    • 0: Success
    • -1: Failure
    int32_t netMessageUriSetQueryParameterValue ( const NetMessageRef & msg , const char * key , const char * value )
    OasisNet.h
    Sets a value for the query key.
    Parameters
    msg  The NetMessage object.
    key  The query key string.
    value  The key value.
    Return Value
    • 0: Success
    • -1: Failure
    bool netMessageIsRequest ( const NetMessageRef & msg )
    OasisNet.h
    Verifies whether it is a request message.
    Parameters
    msg  The NetMessage object.
    Return Value
    • true: It is a request message.
    • false: It is a response message.
    int32_t netMessageSetStatusCodeAndReasonString ( const NetMessageRef & msg , int32_t status_code , const char * reason_string )
    OasisNet.h
    Sets the response code and reason in the message.
    Parameters
    msg  The NetMessage object.
    status_code  The response code.
    reason_string  The reason (explanation) string for the response code.
    Return Value
    • 0: Success
    • -1: Failure
    int32_t netMessageSetContent ( const NetMessageRef & msg , const char * content_type_string , const void * content_data , size_t content_length )
    OasisNet.h
    Stores content data in the message.
    Parameters
    msg  The NetMessage object.
    content_type_string  The Content-Type of the message.
    content_data  The pointer to the content data of the message.
    content_length  The length of the content data, measured in bytes.
    Return Value
    • 0: Success
    • -1: Failure
    ssize_t netMessageGetContentLength ( const NetMessageRef & msg )
    OasisNet.h
    Obtains the content length of the message, measured in bytes.
    Parameters
    msg  The NetMessage object.
    Return Value
    Returns the content length. Returns -1 on failure. Returns 0 if the content is empty.
    int32_t netMessageGetContentType ( const NetMessageRef & msg , std::string & content_type )
    OasisNet.h
    Obtains the Content-Type of the message.
    Parameters
    msg  The NetMessage object.
    content_type  OUT Returns the Content-Type.
    Return Value
    • 0: Success
    • -1: Failure
    ssize_t netMessageGetContent ( const NetMessageRef & msg , std::vector<char> & content )
    OasisNet.h
    Obtains the message content data.
    Parameters
    msg  The NetMessage object.
    content  OUT The vector to return the content data.
    Return Value
    Returns the content length (in bytes) on success. Returns -1 on failure.
    bool netMessageIsChunkedContent ( const NetMessageRef & msg )
    OasisNet.h
    Verifies whether the message content is in chunked format. Messages with large content are split and transmitted as multiple messages. Until fully received, the content length is 0.
    Parameters
    msg  The NetMessage object.
    Return Value
    • true: It is a chunked message.
    • false: It is a single message.
    ssize_t netMessageGetCurrentContentLength ( const NetMessageRef & msg )
    OasisNet.h
    Obtains the current content length of the message, measured in bytes. Obtains the current content length when the message content is large and being received in pieces.
    Parameters
    msg  The NetMessage object.
    Return Value
    Returns the current content length on success. Returns -1 on failure.
    bool netMessageIsContentReady ( const NetMessageRef & msg )
    OasisNet.h
    Verifies whether the message content is completely received and ready. This is useful when receiving large files from the server. Refer to the example below.
    Parameters
    msg  The NetMessage object.
    Return Value
    • true: It is in a ready state.
    • false: It is still downloading.
    int32_t netMessageGetContentFilePath ( const NetMessageRef & msg , std::string & filepath )
    OasisNet.h
    The content path when the content of the message is saved to a file. Saving to a file applies to Content-Types where cache is allowed.
    Parameters
    msg  The NetMessage object.
    filepath  OUT The file path where the content is saved.
    Return Value
    • 0: Success
    • -1: Failure
    bool netMessageIsConnected ( const NetMessageRef & msg )
    OasisNet.h
    Verifies whether the state is connected.
    Parameters
    msg  The NetMessage object.
    Return Value
    • true: It is in a connected state.
    • false: It is in a disconnected state.
    int32_t netMessageAddFieldToMultipartFormData ( const NetMessageRef & msg , const char * field_name , const char * field_value )
    OasisNet.h
    In the case of a POST message, when a user inputs form data, this adds the field name and value to the message. Arbitrary field names and values can be added even if they are not actual form fields.
    Parameters
    msg  The NetMessage object.
    field_name  The field name.
    field_value  The field value.
    Return Value
    • 0: Success
    • -1: Failure
    int32_t netMessageAddContentToMultipartFormData ( const NetMessageRef & msg , const char * field_name , const char * content , size_t content_length , const char * content_type )
    OasisNet.h
    Adds content data to a Multipart message.
    Parameters
    msg  The NetMessage object.
    field_name  The content field name.
    content  The content data.
    content_length  The content data length, measured in bytes.
    content_type  The Content-Type.
    Return Value
    • 0: Success
    • -1: Failure
    int32_t netMessageAddFileToMultipartFormData ( const NetMessageRef & msg , const char * field_name , const char * file_name , const char * content , size_t content_length , const char * content_type )
    OasisNet.h
    Adds a file to a Multipart message. This is useful when transmitting a file to the server side.
    Parameters
    msg  The NetMessage object.
    field_name  The field name.
    file_name  The filename.
    content  The file data.
    content_length  The file data length, measured in bytes.
    content_type  The Content-Type.
    Return Value
    • 0: Success
    • -1: Failure
    int32_t netMessageAddFileToMultipartFormData ( const NetMessageRef & msg , const char * field_name , const char * file_name , const char * file_path , const char * content_type )
    OasisNet.h
    Adds a file to a Multipart message. Use this API when the file size is large. This is useful when transmitting a file to the server side.
    Parameters
    msg  The NetMessage object.
    field_name  The field name.
    file_name  The filename.
    file_path  The path to the file to be transmitted.
    content_type  The Content-Type.
    Return Value
    • 0: Success
    • -1: Failure
    int32_t netMessageSetHeaderField ( const NetMessageRef & msg , const char * name_string , const char * value_string )
    OasisNet.h
    Adds a header field to the message.
    Parameters
    msg  The NetMessage object.
    name_string  The header field name.
    value_string  The header field value.
    Return Value
    • 0: Success
    • -1: Failure
    int32_t netMessageSetCorsHeaderFields ( const NetMessageRef & msg , const NetMessageRef & req_msg , const char * origin = nullptr , const char * methods = nullptr , const char * headers = nullptr , bool allow_credentials = true , bool allow_private_network_access = true , int32_t max_age = 86400 )
    OasisNet.h
    Adds CORS (Cross-Origin Resource Sharing) related header fields to the message.
    Parameters
    msg  The NetMessage object.
    req_msg  The request NetMessage object.
    origin  Adds the Access-Control-Allow-Origin header field. If nullptr, the value "" is assigned. When msg is a response message and the Access-Control-Allow-Origin header field value is "", if the Origin header field of the request message (req_msg) exists, it can be replaced with the value of the Origin header field of the request message. Refer to the descriptions for allow_credentials and allow_private_network_access.
    methods  Adds the Access-Control-Allow-Methods header field. If nullptr, the value "OPTIONS,GET" is assigned.
    headers  Adds the Access-Control-Allow-Headers header field. If nullptr, the value "*" is assigned.
    allow_credentials  This parameter applies when msg is a response message and the Access-Control-Request-Credentials header field exists in the request message (req_msg). It does not apply if the request message is invalid. It sets the Access-Control-Allow-Credentials header field value of the response message to "true" or "false" according to allow_credentials. If the Access-Control-Request-Credentials header field value of the request message is "true" and the origin value is nullptr or "*", the Access-Control-Allow-Origin header field value of the response message is replaced with the Origin header field value of the request message.
    allow_private_network_access  This parameter applies when msg is a response message and the Access-Control-Request-Private-Network header field exists in the request message (req_msg). It does not apply if the request message is invalid. It sets the Access-Control-Allow-Private-Network header field value of the response message to "true" or "false" according to allow_private_network_access. If the Access-Control-Request-Private-Network header field value of the request message is "true" and the origin value is nullptr or "*", the Access-Control-Allow-Origin header field value of the response message is replaced with the Origin header field value of the request message.
    max_age  Adds the Access-Control-Max-Age header field value. If 0, it is set to 86400 seconds.
    Return Value
    • 0: Success
    • -1: Failure
    int32_t netMessageGetHeaderFieldValue ( const NetMessageRef & msg , const char * name_string , std::string & value_string )
    OasisNet.h
    Obtains the header field value of the message.
    Parameters
    msg  The NetMessage object.
    name_string  The header field name.
    value_string  OUT Returns the field value.
    Return Value
    Returns the length of the header field value on success. Returns -1 on failure.
    int32_t netMessageGetHeaderFields ( const NetMessageRef & msg , key_value_map_t & dictionary )
    OasisNet.h
    Obtains the header fields of the message in the format of a key-value map.
    Parameters
    msg  The NetMessage object.
    dictionary  OUT Returns the key-value map for the header field dictionary.
    Return Value
    • 0: Success
    • -1: Failure
    int32_t netMessageGetFormDataFieldValue ( const NetMessageRef & msg , const char * field_name , std::string & field_value )
    OasisNet.h
    Obtains the value of a form data field from the message.
    Parameters
    msg  The NetMessage object.
    field_name  The field name.
    field_value  OUT Returns the field value.
    Return Value
    Returns the length of the field value on success. Returns -1 on failure.
    ssize_t netMessageGetFormDataFileData ( const NetMessageRef & msg , const char * field_name , std::string & content_type , std::string & file_name , char ** file_data_ptr )
    OasisNet.h
    Obtains the data of a form data file field from the message. Although the returned data length value is valid, the *file_data_ptr value can be nullptr, which implies that the file data is saved as a cache file rather than in memory. In this case, the data must be read by explicitly passing the std::vector&lt;char> &file_data argument using the netMessageGetFormDataFileData API below. This function can be called by specifying the file_data_ptr value as nullptr for the simple purpose of verifying the file data type, filename, and file data length.
    Parameters
    msg  The NetMessage object.
    field_name  The field name.
    content_type  OUT Returns the Content-Type.
    file_name  OUT Returns the filename.
    file_data_ptr  OUT If not nullptr, it returns the pointer to the data maintained internally. It does not copy the data. If saved in a cache file rather than in memory, the *file_data_ptr value returns nullptr.
    Return Value
    Returns the data length on success. Returns -1 on failure.
    ssize_t netMessageGetFormDataFileData ( const NetMessageRef & msg , const char * field_name , std::string & content_type , std::string & file_name , std::vector<char> & file_data )
    OasisNet.h
    Stores the data of a form data file field from the message into the transmitted buffer.
    Parameters
    msg  The NetMessage object.
    field_name  The field name.
    content_type  OUT Returns the Content-Type.
    file_name  OUT Returns the filename.
    file_data  OUT The vector where the file data will be saved. If saved in the cache, the cache file content is read and saved.
    Return Value
    Returns the data length on success. Returns -1 on failure.
    ssize_t netMessageSaveFormDataFileDataAs ( const NetMessageRef & msg , const char * field_name , const char * file_path )
    OasisNet.h
    Stores the data of a form data file field from the message into the transmitted file path.
    Parameters
    msg  The NetMessage object.
    field_name  The field name.
    file_path  The file path to be saved.
    Return Value
    Returns the saved file data length on success. Returns -1 on failure.
    int32_t netMessageSetMethod ( const NetMessageRef & msg , const char * method_string )
    OasisNet.h
    Sets the Method of the message.
    Parameters
    msg  The NetMessage object.
    method_string  The Method name.
    Return Value
    • 0: Success
    • -1: Failure
    int32_t netMessageGetMethod ( const NetMessageRef & msg , std::string & method_string )
    OasisNet.h
    Obtains the Method name.
    Parameters
    msg  The NetMessage object.
    method_string  OUT Returns the Method name.
    Return Value
    • 0: Success
    • -1: Failure
    ssize_t netMessageSendFile ( const NetMessageRef & msg , const char * file_path , const char * mime_type_string = nullptr )
    OasisNet.h
    Transmits the file data to the remote client in the background as a response to a file transmission request from the local server. If an error occurs during file transmission, an error response code is transmitted to the client.
    Parameters
    msg  The NetMessage object.
    file_path  The file path.
    mime_type_string  The Content-Type.
    Return Value
    Returns 0 on success, and returns -1 on failure.

    Below is an example of processing when a file transmission request is received from a client on a web server. Error situations are not considered.

    void MyHttpUpStreamDelegate::onRequest(const NetMessageRef &msg) 
    {
      std::string url;
      netMessageUriGetPath(msg, url);
    
      NetMessageRef res = netMessageCreate(msg, false);
    
      std::string path = http_root_dir_path + url;
      if(access(path.c_str(), F_OK) == 0) {
        //get mime type based on extension
        const char *mime_type = get_file_mime_type(path.c_str());   
        if(mime_type == nullptr) {
          //not supported
          netMessageSetStatusCodeAndReasonString(res, 403, "Forbidden");
          netMessagePost(res);  
        } else {
          // Transmits the file.
          netMessageSendFile(res, path.c_str(), mime_type);
        }
      } else {
        netMessageSetStatusCodeAndReasonString(res, 400, "Bad Request");
        netMessagePost(res);    
      }
    }
    
    int32_t netMessagePost ( const NetMessageRef & msg )
    OasisNet.h
    Transmits a message. It returns immediately without waiting for the transmission to finish, and if an error occurs, an error event is delivered through the interface.
    Parameters
    msg  The NetMessage object.
    Return Value
    • 0: Success
    • -1: Failure

    Examples#

    Examples using the message API are located in the documentation for each network component of Oasis.

    Below is an example of a web client receiving a large file from a web server, an example of transmitting form data to a web server, and an example of a web server saving a form data file transmitted by a web client.

    Receiving a Large File from a Web Server#

    Connect to the web server.

    const int32_t timeout = 60000; 
    HttpConnectionRef conn = httpOpenConnection(
                               "https://example.com/data/firmware.img", 
                               timeout, 
                               "/tmp" /* Cache directory */
                               );
    

    Obtain the request message from the connection object, set the Method to GET, and transmit the request message to the server.

    NetMessageRef msg = httpConnectionGetRequestMessage(conn);
    netMessageSetMethod(msg, "GET");
    netMessagePost(msg);
    

    Receive the response header from the server. If there is no response within a certain period of time, it is considered a failure.

    NetMessageRef res_msg;
    wait_count = 0;
    do {
      res_msg = httpConnectionGetResponseHeaderMessage(conn, 1000);
      wait_count++;
    } while(res_msg == nullptr && continuing_ && wait_count*1000 < timeout);
    
    if(res_msg == nullptr || !continuing_) {
      return -1;
    }
    

    Verify the response code. If it is not 200, it is considered an error response.

    std::string reason_string;
    int32_t status_code = netMessageGetStatusCodeAndReasonString(res_msg, reason_string);
    if(status_code != 200) {
      return -1;
    }
    

    Verify the response content length. If the file length is invalid, it is considered an error.

    ssize_t content_length = netMessageGetContentLength(res_msg);
    if(content_length < 0) {
      return -1;
    }
    

    Verify until the file data reception is completely finished through the loop below. If the connection is cut off or the user cancels during reception, it is considered an error.

    do {
      ssize_t current_length = netMessageGetCurrentContentLength(res_msg);
      if(current_length >= 0) {
        // The data length received up to the current point can be verified.
      }
      usleep(1000000);
    } while(netMessageIsConnected(res_msg) && netMessageIsContentReady(res_msg) == false && continuing_);
    
    if(!netMessageIsContentReady(res_msg) || !continuing_) {
      return -1;
    }
    

    Obtain the file path saved in the cache directory (/tmp).

    std::string filepath;
    netMessageGetContentFilePath(res_msg, filepath);
    

    Delete the file after use.

    unlink(filepath.c_str());
    

    Transmitting Form Data to a Web Server#

    Connect to the web server.

    const int32_t timeout = 60000; 
    HttpConnectionRef conn = httpOpenConnection(
                               "https://example.com/api/status/update", 
                               timeout;
    

    Obtain the request message from the connection object and set the Method to POST.

    NetMessageRef msg = httpConnectionGetRequestMessage(conn);
    netMessageSetMethod(msg, "POST");
    

    Configure the form field data and transmit.

    netMessageAddFieldToMultipartFormData(msg, "state", "idle");
    // Specifies the file path to transmit the file data together.
    netMessageAddFileToMultipartFormData(msg, "image", file_name.c_str(), file_path_.c_str(), get_file_mime_type(file_path_.c_str()));
    netMessagePost(msg);
    

    Receive the response header from the server. If there is no response within a certain period of time, it is considered a failure.

    NetMessageRef res_msg;
    wait_count = 0;
    do {
      res_msg = httpConnectionGetResponseHeaderMessage(conn, 1000);
      wait_count++;
    } while(res_msg == nullptr && continuing_ && wait_count*1000 < timeout);
    
    if(res_msg == nullptr || !continuing_) {
      return -1;
    }
    

    Verify the response code. If it is not 200, it is considered an error response.

    std::string reason_string;
    int32_t status_code = netMessageGetStatusCodeAndReasonString(res_msg, reason_string);
    if(status_code != 200) {
      return -1;
    }
    

    Verify the response content length and obtain the response content. Usually, the server transmits response data in JSON format. If the file length of the message is invalid, it is considered an error.

    ssize_t content_length = netMessageGetContentLength(res_msg);
    if(content_length < 0) {
      return -1;
    }
    std::vector<char> res_content;
    netMessageGetContent(res_msg, res_content);
    

    Process the response message.

    Saving a Form Data File on a Web Server#

    Create and start the web server. Specify the cache directory and specify multipart/form-data for the content types to be cached.

    Error situations are not considered in the example.

    parameters["port"] = std::to_string(http_port);
    parameters["root-dir"] = "/var/www/htdocs";
    parameters["content-length-max"] = std::to_string(200*1024*1024);
    parameters["cache-dir"] = "/tmp";
    parameters["cached-content-types"] = "multipart/form-data,multipart/mixed";
    
    std::shared_ptr<MyHttpUpStreamDelegate> http_delegate = std::make_shared<MyHttpUpStreamDelegate>();
    
    HttpServerRef http_server = oasis::createHttpServer(parameters, http_delegate);
    oasis::startHttpServer(http_server);
    

    When a web client transmits the file specified in the "image" file input field of the form data to the web server, the web server saves this response message in the cache folder.

    The web server saves the file uploaded by the web client in the MyHttpUpStreamDelegate::onRequest callback function and sends a response code in JSON.

    virtual void MyHttpUpStreamDelegate::onRequest(const NetMessageRef &msg) {
      std::string url;
      netMessageUriGetPath(msg, url);
    
      if(url == "/api/status/update") {
        std::string content_type, filename;
        ssize_t size = netMessageGetFormDataFileData(msg, "image", content_type, filename, nullptr);
        if(size > 0) {
          char path[PATH_MAX];
          sprintf(path, "/tmp/%s", filename.c_str());
          ssize_t saved_size = netMessageSaveFormDataFileDataAs(msg, "image", path);
        }
    
        NetMessageRef res = netMessageCreate(msg, false);
        netMessageSetStatusCodeAndReasonString(res, 200, "OK");
        netMessageSetHeaderField(res, "Connection", "close");
        std::string json_string = R"({ "result":"OK" })";
        netMessageSetContent(res, "application/json", json_string.c_str(), json_string.length());
        netMessagePost(res);
      }
    }