Exemple #1
0
static GString *gmime_message_to_json(GMimeMessage *message, guint content_option) {
  MessageData *mdata = convert_message(message, content_option);


  JSON_Value *root_value = json_value_init_object();
  JSON_Object *root_object = json_value_get_object(root_value);

  json_object_set_value(root_object,  "from",        addresses_list_to_json(mdata->from));
  json_object_set_value(root_object,  "to",          addresses_list_to_json(mdata->to));
  json_object_set_value(root_object,  "replyTo",     addresses_list_to_json(mdata->reply_to));
  json_object_set_value(root_object,  "cc",          addresses_list_to_json(mdata->cc));
  json_object_set_value(root_object,  "bcc",         addresses_list_to_json(mdata->bcc));
  json_object_set_string(root_object, "messageId",   mdata->message_id);
  json_object_set_string(root_object, "subject",     mdata->subject);
  json_object_set_string(root_object, "date",        mdata->date);

  json_object_set_value(root_object, "inReplyTo",   references_to_json(mdata->in_reply_to));
  json_object_set_value(root_object, "references",  references_to_json(mdata->references));

  json_object_set_value(root_object,  "text",        message_body_to_json(mdata->text));
  json_object_set_value(root_object,  "html",        message_body_to_json(mdata->html));
  json_object_set_value(root_object,  "attachments", message_attachments_list_to_json(mdata->attachments));

  free_message_data(mdata);
  gchar *serialized_string = json_serialize_to_string(root_value);
  json_value_free(root_value);

  GString *json_string = g_string_new(serialized_string);
  g_free(serialized_string);

  return json_string;
}
Exemple #2
0
void test_suite_2_with_comments(void) {
    const char *filename = "tests/test_2_comments.txt";
    JSON_Value *root_value = NULL;
    root_value = json_parse_file_with_comments(filename);
    test_suite_2(root_value);
    TEST(json_value_equals(root_value, json_parse_string(json_serialize_to_string(root_value))));
    json_value_free(root_value);
}
Exemple #3
0
void test_suite_1(void) {
	JSON_Value *val;
	TEST((val = json_parse_file("tests/test_1_1.txt")) != NULL);
	TEST(json_value_equals(json_parse_string(json_serialize_to_string(val)), val));
	TEST(json_value_equals(json_parse_string(json_serialize_to_string_pretty(val)), val));
	if (val) { json_value_free(val); }

	TEST((val = json_parse_file("tests/test_1_2.txt")) != NULL);
	TEST(json_value_equals(json_parse_string(json_serialize_to_string(val)), val));
	TEST(json_value_equals(json_parse_string(json_serialize_to_string_pretty(val)), val));
	if (val) { json_value_free(val); }

	TEST((val = json_parse_file("tests/test_1_3.txt")) != NULL);
	TEST(json_value_equals(json_parse_string(json_serialize_to_string(val)), val));
	TEST(json_value_equals(json_parse_string(json_serialize_to_string_pretty(val)), val));
	if (val) { json_value_free(val); }

	TEST((val = json_parse_file_with_comments("tests/test_1_1.txt")) != NULL);
	TEST(json_value_equals(json_parse_string(json_serialize_to_string(val)), val));
	TEST(json_value_equals(json_parse_string(json_serialize_to_string_pretty(val)), val));
	if (val) { json_value_free(val); }

	TEST((val = json_parse_file_with_comments("tests/test_1_2.txt")) != NULL);
	TEST(json_value_equals(json_parse_string(json_serialize_to_string(val)), val));
	TEST(json_value_equals(json_parse_string(json_serialize_to_string_pretty(val)), val));
	if (val) { json_value_free(val); }

	TEST((val = json_parse_file_with_comments("tests/test_1_3.txt")) != NULL);
	TEST(json_value_equals(json_parse_string(json_serialize_to_string(val)), val));
	TEST(json_value_equals(json_parse_string(json_serialize_to_string_pretty(val)), val));
	if (val) { json_value_free(val); }
}
Exemple #4
0
char* pack_message(int fields, char* contents[]) {
    if (fields == 0) return NULL;

    JSON_Value *values = json_value_init_array();
    JSON_Array *array = json_value_get_array(values);
    int i;
    for (i = 0; i < fields; i++) {
        char* c = contents[i];
        json_array_append_string(array, contents[i]);
    }

    return json_serialize_to_string(values);
}
Exemple #5
0
void serialization_example(void) {
    JSON_Value *root_value = json_value_init_object();
    JSON_Object *root_object = json_value_get_object(root_value);
    char *serialized_string = NULL;
    json_object_set_string(root_object, "name", "John Smith");
    json_object_set_number(root_object, "age", 25);
    json_object_dotset_string(root_object, "address.city", "Cupertino");
    json_object_dotset_value(root_object, "contact.emails",
                             json_parse_string("[\"[email protected]\", \"[email protected]\"]"));
    serialized_string = json_serialize_to_string(root_value);
    puts(serialized_string);
    json_free_serialized_string(serialized_string);
    json_value_free(root_value);
}
Exemple #6
0
char *djcs_export_public_key(djcs_public_key *pk)
{
    char *buffer;
    char *retstr;

    JSON_Value *root = json_value_init_object();
    JSON_Object *obj  = json_value_get_object(root);
    buffer = mpz_get_str(NULL, HCS_INTERNAL_BASE, pk->n[0]);
    json_object_set_number(obj, "s", pk->s);
    json_object_set_string(obj, "n", buffer);
    retstr = json_serialize_to_string(root);

    json_value_free(root);
    free(buffer);
    return retstr;
}
Exemple #7
0
void test_suite_8(void) {
	const char *filename = "tests/test_2.txt";
	const char *temp_filename = "tests/test_2_serialized.txt";
	JSON_Value *a = NULL;
	JSON_Value *b = NULL;
	char *buf = NULL;
	size_t serialization_size = 0;
	a = json_parse_file(filename);
	TEST(json_serialize_to_file(a, temp_filename) == JSONSuccess);
	b = json_parse_file(temp_filename);
	TEST(json_value_equals(a, b));
	remove(temp_filename);
	serialization_size = json_serialization_size(a);
	buf = json_serialize_to_string(a);
	TEST((strlen(buf) + 1) == serialization_size);
}
char* querySpecification_serializeToJson(const PROVISIONING_QUERY_SPECIFICATION* query_spec)
{
    char* result = NULL;
    char* serialized_string = NULL;
    JSON_Value* root_value = NULL;

    if (query_spec == NULL)
    {
        LogError("Invalid query specification");
    }
    else if (query_spec->version != PROVISIONING_QUERY_SPECIFICATION_VERSION_1)
    {
        LogError("Invalid version");
    }
    else if ((root_value = querySpecification_toJson(query_spec)) == NULL)
    {
        LogError("Creating json object failed");
    }
    else if ((serialized_string = json_serialize_to_string(root_value)) == NULL)
    {
        LogError("Failed to serialize to JSON");
    }
    else if (mallocAndStrcpy_s(&result, serialized_string) != 0)
    {
        LogError("Failed to copy serialized string");
    }

    if (root_value != NULL)
    {
        json_value_free(root_value);
        root_value = NULL;
    }
    if (serialized_string != NULL)
    {
        json_free_serialized_string(serialized_string);
        serialized_string = NULL;
    }

    return result;
}
Exemple #9
0
char *djcs_export_private_key(djcs_private_key *vk)
{
    char *buffer;
    char *retstr;

    /* Allocate space for largest buffer output value used */
    size_t buffer_size = mpz_sizeinbase((mpz_cmp(vk->n[0], vk->d) >= 0
            ? vk->n[0] : vk->d), HCS_INTERNAL_BASE) + 2;
    buffer = malloc(buffer_size);

    JSON_Value *root = json_value_init_object();
    JSON_Object *obj = json_value_get_object(root);
    json_object_set_number(obj, "s", vk->s);
    mpz_get_str(buffer, HCS_INTERNAL_BASE, vk->n[0]);
    json_object_set_string(obj, "n", buffer);
    mpz_get_str(buffer, HCS_INTERNAL_BASE, vk->d);
    json_object_set_string(obj, "d", buffer);
    retstr = json_serialize_to_string(root);

    json_value_free(root);
    free(buffer);
    return retstr;
}
void APP2_Tasks ( void )
{
/* Update the application state machine based
     * on the current state */

    switch(app2Data.state)
    {
        case APP2_STATE_INIT:

            /* Open the device layer */
            app2Data.deviceHandle = USB_DEVICE_Open( USB_DEVICE_INDEX_0, DRV_IO_INTENT_READWRITE );

            if(app2Data.deviceHandle != USB_DEVICE_HANDLE_INVALID)
            {
                /* Register a callback with device layer to get event notification (for end point 0) */
                USB_DEVICE_EventHandlerSet(app2Data.deviceHandle, APP_USBDeviceEventHandler, 0);

                app2Data.state = APP2_STATE_WAIT_FOR_CONFIGURATION;
            }
            else
            {
                /* The Device Layer is not ready to be opened. We should try
                 * again later. */
            }

            break;

        case APP2_STATE_WAIT_FOR_CONFIGURATION:

            /* Check if the device was configured */
            if(app2Data.isConfigured)
            {
                app2Data.state = APP2_STATE_SCHEDULE_READ;
            }
            break;
            
        case APP2_STATE_SCHEDULE_READ:
            if(APP_StateReset())
            {
                break;
            }
            
            /* If a read is complete, then schedule a read
            * else wait for the current read to complete */
            
            app2Data.state = APP2_STATE_WAIT_FOR_READ_COMPLETE;
            if(app2Data.isReadComplete == true)
            {
                app2Data.isReadComplete = false;
                app2Data.readTransferHandle =  USB_DEVICE_CDC_TRANSFER_HANDLE_INVALID;
                
                USB_DEVICE_CDC_Read (USB_DEVICE_CDC_INDEX_0,
                        &app2Data.readTransferHandle, app2Data.readBuffer,
                        APP_READ_BUFFER_SIZE);
                
                if(app2Data.readTransferHandle == USB_DEVICE_CDC_TRANSFER_HANDLE_INVALID)
                {
                    app2Data.state = APP2_STATE_ERROR;
                    break;
                }
            }
            break;

        case APP2_STATE_WAIT_FOR_READ_COMPLETE:
            
            if(APP_StateReset())
            {
                break;
            }
            
            if(app2Data.isReadComplete == true)
            {            
                // Check for delimiter
                int res = APP_CheckForMessage(app2Data.readBuffer);
                if(res == MESSAGE_BAD_POINTER)
                {
                    // Do something
                    break;
                }
                else if(res == MESSAGE_NO_DELIMITER)
                {
                    strcat(messageBuffer, app2Data.readBuffer);
                    memset(app2Data.readBuffer, '\0', APP_READ_BUFFER_SIZE);
                    app2Data.state = APP2_STATE_SCHEDULE_READ;
                    break;
                }
 
                strcat(messageBuffer, app2Data.readBuffer);
                // Parse for the command being sent so we can handle it
                int command = APP_ParseCommand(messageBuffer);

                // Lets build our response message
                // First initialize the JSON value and object from parson library
                JSON_Value *rootValue = json_value_init_object();
                JSON_Object *rootObject = json_value_get_object(rootValue);
                char *serializedString = NULL;  
                    
                // Build response and handle the command
                switch(command)
                {
                    // If hello command, respond with discovery packet 
                    case COMMAND_HELLO:
                            json_object_dotset_string(rootObject, "message.command", "discovery");
                            json_object_dotset_string(rootObject, "message.discovery_object.title", APP_TITLE);
                            json_object_dotset_string(rootObject, "message.discovery_object.part_number", APP_PART_NUMBER);
                            json_object_dotset_string(rootObject, "message.discovery_object.mac_address", appData.macAddress);
                            json_object_dotset_string(rootObject, "message.discovery_object.firmware_version", APP_FIRMWARE_VERSION);
                            json_object_dotset_string(rootObject, "message.discovery_object.harmony_version", SYS_VERSION_STR);
                            json_object_dotset_boolean(rootObject, "message.discovery_object.is_commissioned", appData.isCommissioned);
                        break;
                        
                    // If configuration command, respond with ACK/NACK 
                    case COMMAND_CONFIGURE:
                    {
                        if(appData.isCommissioned == false)
                        {
                            JSON_Value *messageRoot = json_parse_string(messageBuffer);
                            if(json_value_get_type(messageRoot) != JSONObject)
                            {
                                BuildAckNackMessage(rootObject, "nack", "Invalid JSON Object");
                                break;
                            }
                            else
                            {
                                JSON_Object *messageObject = json_value_get_object(messageRoot);
                                if( json_object_dotget_string(messageObject, "message.configuration_object.aws_iot_endpoint_address") != NULL &&
                                    json_object_dotget_string(messageObject, "message.configuration_object.aws_certificate") != NULL &&
                                    json_object_dotget_string(messageObject, "message.configuration_object.aws_certificate_private_key") != NULL )
                                {
                                    json_object_dotset_string(rootObject, "message.command", "ack");
                                    json_object_dotset_string(rootObject, "message.ack_nack_message", "Writing commission parameters to flash");
                                    sprintf((char *)appData.host, json_object_dotget_string(messageObject, "message.configuration_object.aws_iot_endpoint_address"));
                                    sprintf((char *)appData.clientCert, json_object_dotget_string(messageObject, "message.configuration_object.aws_certificate"));
                                    sprintf((char *)appData.clientKey, json_object_dotget_string(messageObject, "message.configuration_object.aws_certificate_private_key"));
                                    appData.isCommissioned = true;
                                    appData.writeToNVM = true;
                                }
                                else
                                {
                                    BuildAckNackMessage(rootObject, "nack", "Invalid commission parameters");
                                    break;
                                }
                            } 
                        }
                        else
                        {
                            BuildAckNackMessage(rootObject, "nack", "Already commissioned");
                        }                    
                        break;
                    }
                    
                    case COMMAND_DEBUG_SET:
                    {
                        JSON_Value *messageRoot = json_parse_string(messageBuffer);
                        if(json_value_get_type(messageRoot) != JSONObject)
                        {
                            BuildAckNackMessage(rootObject, "nack", "Invalid JSON Object");
                            break;
                        }
                        JSON_Object *messageObject = json_value_get_object(messageRoot);
                        if(messageObject == NULL)
                        {
                            BuildAckNackMessage(rootObject, "nack", "NULL Pointer");
                            break;
                        }
                        BuildAckNackMessage(rootObject, "ack", "Received debug set");
                        int DebugMessage = DEBUG_UPDATE;
                        xQueueSendToFront(app2Data.debugQueue, &DebugMessage, 1);
                        if(json_object_dotget_boolean(messageObject, "message.debug_set_object.set"))
                            appData.debugSet = true;
                        else
                            appData.debugSet = false;
                        break;
                    }
                    
                    case COMMAND_BAD_JSON:
                            BuildAckNackMessage(rootObject, "nack", "Bad JSON");
                        break;
                    
                    case COMMAND_INVALID:
                            BuildAckNackMessage(rootObject, "nack", "Command Invalid");
                        break;
                        
                    default:
                            BuildAckNackMessage(rootObject, "nack", "Something went wrong");
                        break;
                }
                memset(app2Data.writeBuffer, '\0', APP_WRITE_BUFFER_SIZE);
                // With our response built, serialize the response into a string
                serializedString = json_serialize_to_string(rootValue);
                strcpy(app2Data.writeBuffer, serializedString);
                // Find length of string and add delimiter to end
                app2Data.writeBuffer[strlen(app2Data.writeBuffer)] = '\r';
                
                json_free_serialized_string(serializedString);  
                // Reset string buffers
                memset(app2Data.readBuffer, '\0', APP_READ_BUFFER_SIZE);
                memset(messageBuffer, '\0', APP_MESSAGE_BUFFER_SIZE);
                app2Data.state = APP2_STATE_SCHEDULE_WRITE;
            }
            else
            {
                app2Data.state = APP2_STATE_WAIT_FOR_READ_COMPLETE;
                if( uxQueueMessagesWaiting( app2Data.debugQueue ) > 0 )
                {
                    int debugMessageNumber;
                    xQueueReceive( app2Data.debugQueue, &debugMessageNumber, 1 );
                    sprintf(app2Data.writeBuffer,                       
                    "{"                                                  
                         "\"message\":{"                                 
                            "\"command\":\"debug\","
                                "\"debug_object\":{"
                                    "\"board_ip_address\":\"%d.%d.%d.%d\","
                                    "\"aws_iot_endpoint\":\"%s\","
                                    "\"mac_address\":\"%s\","
                                    "\"socket_connected\":%s,"
                                    "\"mqtt_connected\":%s,"
                                    "\"raw_message\":\"%s\""
                    "}}}\r",
                    appData.board_ipAddr.v4Add.v[0],
                    appData.board_ipAddr.v4Add.v[1],
                    appData.board_ipAddr.v4Add.v[2],
                    appData.board_ipAddr.v4Add.v[3],
                    appData.host,
                    appData.macAddress,
                    (appData.socket_connected ? "true" : "false"),
                    (appData.mqtt_connected ? "true" : "false"),
                    APP_ReturnDebugCodeToString(debugMessageNumber));
                    app2Data.state = APP2_STATE_SCHEDULE_DEBUG_WRITE;
                }
            }
            break;
            
                        
        case APP2_STATE_SCHEDULE_WRITE:

            if(APP_StateReset())
            {
                break;
            }

            app2Data.writeTransferHandle = USB_DEVICE_CDC_TRANSFER_HANDLE_INVALID;
            app2Data.isWriteComplete = false;
            app2Data.state = APP2_STATE_WAIT_FOR_WRITE_COMPLETE;

            USB_DEVICE_CDC_Write(USB_DEVICE_CDC_INDEX_0,
                &app2Data.writeTransferHandle, app2Data.writeBuffer, strlen(app2Data.writeBuffer),
                USB_DEVICE_CDC_TRANSFER_FLAGS_DATA_COMPLETE);

            break;
            
        case APP2_STATE_WAIT_FOR_WRITE_COMPLETE:

            if(APP_StateReset())
            {
                break;
            }

            /* Check if message sent.  The isWriteComplete
             * flag gets updated in the CDC event handler */

            if(app2Data.isWriteComplete == true)
            {
                app2Data.state = APP2_STATE_SCHEDULE_READ;
            }
            break;
            
        case APP2_STATE_SCHEDULE_DEBUG_WRITE:
            if(APP_StateReset())
            {
                break;
            }

            app2Data.writeTransferHandle = USB_DEVICE_CDC_TRANSFER_HANDLE_INVALID;
            app2Data.isWriteComplete = false;
            app2Data.state = APP2_STATE_WAIT_FOR_DEBUG_WRITE_COMPLETE;

            USB_DEVICE_CDC_Write(USB_DEVICE_CDC_INDEX_0,
                &app2Data.writeTransferHandle, app2Data.writeBuffer, strlen(app2Data.writeBuffer),
                USB_DEVICE_CDC_TRANSFER_FLAGS_DATA_COMPLETE);

            break;
            
        case APP2_STATE_WAIT_FOR_DEBUG_WRITE_COMPLETE:

            if(APP_StateReset())
            {
                break;
            }

            /* Check if message sent.  The isWriteComplete
             * flag gets updated in the CDC event handler */

            if(app2Data.isWriteComplete == true)
            {
                app2Data.state = APP2_STATE_WAIT_FOR_READ_COMPLETE;
            }
            break;

        case APP2_STATE_ERROR:
            break;
        default:
            break;
    }
}
static MODULE_HANDLE NativeModuleHost_Create(BROKER_HANDLE broker, const void* configuration)
{
    MODULE_HOST * result;
    if (broker == NULL || configuration == NULL)
    {
        /*Codes_SRS_NATIVEMODULEHOST_17_008: [ NativeModuleHost_Create shall return NULL if broker is NULL. ]*/
        /*Codes_SRS_NATIVEMODULEHOST_17_009: [ NativeModuleHost_Create shall return NULL if configuration does not contain valid JSON. ]*/
        LogError("broker [%p] or configuration [%p] is NULL, both are required", broker, configuration);
        result = NULL;
    }
    else
    {
        /*Codes_SRS_NATIVEMODULEHOST_17_010: [ NativeModuleHost_Create shall intialize the Module_Loader. ]*/
        if (ModuleLoader_Initialize() != MODULE_LOADER_SUCCESS)
        {
            /*Codes_SRS_NATIVEMODULEHOST_17_026: [ If any step above fails, then NativeModuleHost_Create shall free all resources allocated and return NULL. ]*/
            LogError("ModuleLoader_Initialize failed");
            result = NULL;
        }
        else
        {
            /*Codes_SRS_NATIVEMODULEHOST_17_011: [ NativeModuleHost_Create shall parse the configuration JSON. ]*/
            char * outprocess_module_args = (char *)configuration;
            JSON_Value *root_value = json_parse_string(outprocess_module_args);
            JSON_Object * module_host_args;
            if ((root_value == NULL) ||
                ((module_host_args = json_value_get_object(root_value)) == NULL))
            {
                if (root_value != NULL)
                {
                    json_value_free(root_value);
                }
                LogError("NativeModuleHost_Create could not parse arguments as JSON");
                result = NULL;
            }
            else
            {
                /*Codes_SRS_NATIVEMODULEHOST_17_035: [ If the "outprocess.loaders" array exists in the configuration JSON, NativeModuleHost_Create shall initialize the Module_Loader from this array. ]*/
                JSON_Value * loaders_array = json_object_get_value(module_host_args, OOP_MODULE_LOADERS_ARRAY_KEY);
                if ((loaders_array != NULL) &&
                    (ModuleLoader_InitializeFromJson(loaders_array) != MODULE_LOADER_SUCCESS))
                {
                    LogError("NativeModuleHost_Create could not extract loaders array from module arguments.");
                    result = NULL;
                }
                else
                {
                    /*Codes_SRS_NATIVEMODULEHOST_17_012: [ NativeModuleHost_Create shall get the "outprocess.loader" object from the configuration JSON. ]*/
                    JSON_Object * loader_args = json_object_get_object(module_host_args, OOP_MODULE_LOADER_KEY);
                    if (loader_args == NULL)
                    {
                        LogError("NativeModuleHost_Create could not get loader arguments.");
                        result = NULL;
                    }
                    else
                    {
                        GATEWAY_MODULE_LOADER_INFO loader_info;
                        if (parse_loader(loader_args, &loader_info) != 0)
                        {
                            /*Codes_SRS_NATIVEMODULEHOST_17_026: [ If any step above fails, then NativeModuleHost_Create shall free all resources allocated and return NULL. ]*/
                            LogError("NativeModuleHost_Create could not extract loader information from loader arguments.");
                            result = NULL;
                        }
                        else
                        {
                            // Have loader and entrypoint now, get module.
                            result = (MODULE_HOST*)malloc(sizeof(MODULE_HOST));
							if (result == NULL)
							{
								LogError("NativeModuleHost_Create could not allocate module.");
								result = NULL;
							}
							else
							{
								/*Codes_SRS_NATIVEMODULEHOST_17_018: [ NativeModuleHost_Create shall get the "module.args" object from the configuration JSON. ]*/
								JSON_Value * module_args = json_object_get_value(module_host_args, OOP_MODULE_ARGS_KEY);
								char * module_args_string = json_serialize_to_string(module_args);
								if (module_create(result, broker, &loader_info, module_args_string) != 0)
								{
									/*Codes_SRS_NATIVEMODULEHOST_17_026: [ If any step above fails, then NativeModuleHost_Create shall free all resources allocated and return NULL. ]*/
									LogError("NativeModuleHost_Create could not load module.");
									free(result);
									result = NULL;
								}
								/*Codes_SRS_NATIVEMODULEHOST_17_024: [ NativeModuleHost_Create shall free all resources used during module loading. ]*/
								json_free_serialized_string(module_args_string);
							}
                            loader_info.loader->api->FreeEntrypoint(loader_info.loader, loader_info.entrypoint);
                        }
                    }
                }
                /*Codes_SRS_NATIVEMODULEHOST_17_024: [ NativeModuleHost_Create shall free all resources used during module loading. ]*/
                json_value_free(root_value);
            }
            if (result == NULL)
            {
                // failed to create a module, give up entirely.
                /*Codes_SRS_NATIVEMODULEHOST_17_026: [ If any step above fails, then NativeModuleHost_Create shall free all resources allocated and return NULL. ]*/
                ModuleLoader_Destroy();
            }
        }
    }
    return result;
}
static IOTHUB_DEVICE_METHOD_RESULT parseResponseJson(BUFFER_HANDLE responseJson, int* responseStatus, unsigned char** responsePayload, size_t* responsePayloadSize)
{
    IOTHUB_DEVICE_METHOD_RESULT result;
    JSON_Value* root_value;
    JSON_Object* json_object;
    JSON_Value* statusJsonValue;
    JSON_Value* payloadJsonValue;
    char* payload;
    STRING_HANDLE jsonStringHandle;
    const char* jsonStr;
    unsigned char* bufferStr;
    
    if ((bufferStr = BUFFER_u_char(responseJson)) == NULL)
    {
        LogError("BUFFER_u_char failed");
        result = IOTHUB_DEVICE_METHOD_ERROR;
    }
    else if ((jsonStringHandle = STRING_from_byte_array(bufferStr, BUFFER_length(responseJson))) == NULL)
    {
        LogError("STRING_construct_n failed");
        result = IOTHUB_DEVICE_METHOD_ERROR;
    }
    else if ((jsonStr = STRING_c_str(jsonStringHandle)) == NULL)
    {
        LogError("STRING_c_str failed");
        STRING_delete(jsonStringHandle);
        result = IOTHUB_DEVICE_METHOD_ERROR;
    }
    else if ((root_value = json_parse_string(jsonStr)) == NULL)
    {
        LogError("json_parse_string failed");
        STRING_delete(jsonStringHandle);
        result = IOTHUB_DEVICE_METHOD_ERROR;
    }
    else if ((json_object = json_value_get_object(root_value)) == NULL)
    {
        LogError("json_value_get_object failed");
        STRING_delete(jsonStringHandle);
        json_value_free(root_value);
        result = IOTHUB_DEVICE_METHOD_ERROR;
    }
    else if ((statusJsonValue = json_object_get_value(json_object, "status")) == NULL)
    {
        LogError("json_object_get_value failed for status");
        STRING_delete(jsonStringHandle);
        json_value_free(root_value);
        result = IOTHUB_DEVICE_METHOD_ERROR;
    }
    else if ((payloadJsonValue = json_object_get_value(json_object, "payload")) == NULL)
    {
        LogError("json_object_get_value failed for payload");
        STRING_delete(jsonStringHandle);
        json_value_free(root_value);
        result = IOTHUB_DEVICE_METHOD_ERROR;
    }
    else if ((payload = json_serialize_to_string(payloadJsonValue)) == NULL)
    {
        LogError("json_serialize_to_string failed for payload");
        STRING_delete(jsonStringHandle);
        json_value_free(root_value);
        result = IOTHUB_DEVICE_METHOD_ERROR;
    }
    else
    {
        *responseStatus = (int)json_value_get_number(statusJsonValue);
        *responsePayload = (unsigned char *)payload;
        *responsePayloadSize = strlen(payload);

        STRING_delete(jsonStringHandle);
        json_value_free(root_value);
        result = IOTHUB_DEVICE_METHOD_OK;
    }

    return result;
}
Exemple #13
0
static ACVP_RESULT execute_network_action(ACVP_CTX *ctx,
                                          ACVP_NET_ACTION action,
                                          char *url,
                                          char *data,
                                          int data_len,
                                          int *curl_code) {
    ACVP_RESULT result = 0;
    char *resp = NULL;
    char large_url[ACVP_ATTR_URL_MAX + 1] = {0};
    int large_submission = 0;
    int resp_len = 0;
    int rc = 0;

    switch(action) {
    case ACVP_NET_GET:
    case ACVP_NET_GET_VS:
    case ACVP_NET_GET_VS_RESULT:
    case ACVP_NET_GET_VS_SAMPLE:
        rc = acvp_curl_http_get(ctx, url);
        break;

    case ACVP_NET_POST:
    case ACVP_NET_POST_LOGIN:
    case ACVP_NET_POST_REG:
        rc = acvp_curl_http_post(ctx, url, data, data_len);
        break;

    case ACVP_NET_POST_VS_RESP:
        resp = json_serialize_to_string(ctx->kat_resp, &resp_len);
        if (!resp) {
            ACVP_LOG_ERR("Faled to serialize JSON to string");
            return ACVP_JSON_ERR;
        }
        json_value_free(ctx->kat_resp);
        ctx->kat_resp = NULL;

        if (ctx->post_size_constraint && resp_len > ctx->post_size_constraint) {
            /* Determine if this POST body goes over the "constraint" */
            large_submission = 1;
        }

        if (large_submission) {
            /*
             * Need to tell the server about this large submission.
             * The server will supply us with a one-time "large" URL;
             */
            result = acvp_notify_large(ctx, url, large_url, resp_len);
            if (result != ACVP_SUCCESS) goto end;

            rc = acvp_curl_http_post(ctx, large_url, resp, resp_len);
        } else {
            rc = acvp_curl_http_post(ctx, url, resp, resp_len);
        }

        break;

    default:
        ACVP_LOG_ERR("Unknown ACVP_NET_ACTION");
        return ACVP_INVALID_ARG;
    }

    /* Peek at the HTTP code */
    result = inspect_http_code(ctx, rc);

    if (result != ACVP_SUCCESS) {
        if (result == ACVP_JWT_EXPIRED &&
            action != ACVP_NET_POST_LOGIN) {
            /*
             * Expired JWT
             * We are going to refresh the session
             * and try to obtain a new JWT!
             * This should not ever happen during "login"...
             * and we need to avoid an infinite loop (via acvp_refesh).
             */
            ACVP_LOG_ERR("JWT authorization has timed out, curl rc=%d.\n"
                         "Refreshing session...", rc);

            result = acvp_refresh(ctx);
            if (result != ACVP_SUCCESS) {
                ACVP_LOG_ERR("JWT refresh failed.");
                goto end;
            }

            /* Try action again after the refresh */
            switch(action) {
            case ACVP_NET_GET:
            case ACVP_NET_GET_VS:
            case ACVP_NET_GET_VS_RESULT:
            case ACVP_NET_GET_VS_SAMPLE:
                rc = acvp_curl_http_get(ctx, url);
                break;

            case ACVP_NET_POST:
            case ACVP_NET_POST_REG:
                rc = acvp_curl_http_post(ctx, url, data, data_len);
                break;

            case ACVP_NET_POST_VS_RESP:
                if (large_submission) {
                    rc = acvp_curl_http_post(ctx, large_url, resp, resp_len);
                } else {
                    rc = acvp_curl_http_post(ctx, url, resp, resp_len);
                }
                break;

            case ACVP_NET_POST_LOGIN:
                ACVP_LOG_ERR("We should never be here!");
                break;
            }

            result = inspect_http_code(ctx, rc);
            if (result != ACVP_SUCCESS) {
                ACVP_LOG_ERR("Refreshed + retried, HTTP transport fails. curl rc=%d\n", rc);
                goto end;
            }
        } else if (result == ACVP_JWT_INVALID) {
            /*
             * Invalid JWT
             */
            ACVP_LOG_ERR("JWT invalid. curl rc=%d.\n", rc);
            goto end;
        }

        /* Generic error */
        goto end;
    }

    result = ACVP_SUCCESS;

end:
    if (resp) json_free_serialized_string(resp);

    *curl_code = rc;

    return result;
}