static void* construct_create_message(OUTPROCESS_HANDLE_DATA* handleData, int32_t * creationMessageSize)
{
	void * result;
	uint32_t uri_length = STRING_length(handleData->message_uri);
	char * uri_string = (char*)STRING_c_str(handleData->message_uri);
	uint32_t args_length = STRING_length(handleData->module_args);
	char * args_string = (char*)STRING_c_str(handleData->module_args);
	if (uri_length == 0 || uri_string == NULL || 
		args_length == 0 || args_string == NULL)
	{
		result = NULL;
	}
	else
	{
		/*Codes_SRS_OUTPROCESS_MODULE_17_012: [ This function shall construct a Create Message from configuration. ]*/

		CONTROL_MESSAGE_MODULE_CREATE create_msg =
		{
			{
				CONTROL_MESSAGE_VERSION_CURRENT,	/*version*/
				CONTROL_MESSAGE_TYPE_MODULE_CREATE	/*type*/
			},
			GATEWAY_MESSAGE_VERSION_CURRENT,		/*gateway_message_version*/
			{
				uri_length + 1,						/*uri_size (+1 for null)*/
				(uint8_t)NN_PAIR,					/*uri_type*/
				uri_string							/*uri*/
			},
			args_length + 1,	/*args_size;(+1 for null)*/
			args_string			/*args;*/
		};
		result = serialize_control_message((CONTROL_MESSAGE *)&create_msg, creationMessageSize);
	}
	return result;
}
static void sendHttpRequestMethodExpectedCalls()
{
    STRICT_EXPECTED_CALL(environment_get_variable(IGNORED_PTR_ARG)).CallCannotFail();
    STRICT_EXPECTED_CALL(HTTPHeaders_Alloc());
    STRICT_EXPECTED_CALL(HTTPHeaders_AddHeaderNameValuePair(IGNORED_PTR_ARG, IGNORED_PTR_ARG, IGNORED_PTR_ARG));
    STRICT_EXPECTED_CALL(HTTPHeaders_AddHeaderNameValuePair(IGNORED_PTR_ARG, IGNORED_PTR_ARG, IGNORED_PTR_ARG));
    STRICT_EXPECTED_CALL(gballoc_malloc(IGNORED_NUM_ARG));
    STRICT_EXPECTED_CALL(UniqueId_Generate(IGNORED_PTR_ARG, IGNORED_NUM_ARG));
    STRICT_EXPECTED_CALL(HTTPHeaders_AddHeaderNameValuePair(IGNORED_PTR_ARG, IGNORED_PTR_ARG, IGNORED_PTR_ARG));
    STRICT_EXPECTED_CALL(HTTPHeaders_AddHeaderNameValuePair(IGNORED_PTR_ARG, IGNORED_PTR_ARG, IGNORED_PTR_ARG));
    STRICT_EXPECTED_CALL(HTTPHeaders_AddHeaderNameValuePair(IGNORED_PTR_ARG, IGNORED_PTR_ARG, IGNORED_PTR_ARG));
    STRICT_EXPECTED_CALL(gballoc_free(IGNORED_PTR_ARG));    //cannot fail

    STRICT_EXPECTED_CALL(STRING_c_str(IGNORED_PTR_ARG));
    STRICT_EXPECTED_CALL(IoTHubClient_Auth_Get_SasToken(IGNORED_PTR_ARG, IGNORED_PTR_ARG, IGNORED_NUM_ARG, IGNORED_PTR_ARG));
    STRICT_EXPECTED_CALL(HTTPHeaders_ReplaceHeaderNameValuePair(IGNORED_PTR_ARG, IGNORED_PTR_ARG, IGNORED_PTR_ARG));
    STRICT_EXPECTED_CALL(STRING_c_str(IGNORED_PTR_ARG));
    STRICT_EXPECTED_CALL(HTTPHeaders_ReplaceHeaderNameValuePair(IGNORED_PTR_ARG, IGNORED_PTR_ARG, IGNORED_PTR_ARG));
    STRICT_EXPECTED_CALL(STRING_delete(IGNORED_PTR_ARG));   //cannot fail
    STRICT_EXPECTED_CALL(STRING_delete(IGNORED_PTR_ARG));   //cannot fail
    STRICT_EXPECTED_CALL(gballoc_free(IGNORED_PTR_ARG));    //cannot fail

    STRICT_EXPECTED_CALL(STRING_c_str(IGNORED_PTR_ARG));
    STRICT_EXPECTED_CALL(HTTPAPIEX_Create(IGNORED_PTR_ARG));
    STRICT_EXPECTED_CALL(IoTHubClient_Auth_Get_TrustBundle(IGNORED_PTR_ARG, IGNORED_PTR_ARG));
    STRICT_EXPECTED_CALL(HTTPAPIEX_SetOption(IGNORED_PTR_ARG, IGNORED_PTR_ARG, IGNORED_PTR_ARG));
    STRICT_EXPECTED_CALL(HTTPAPIEX_ExecuteRequest(IGNORED_PTR_ARG, HTTPAPI_REQUEST_POST, IGNORED_PTR_ARG, IGNORED_PTR_ARG, IGNORED_PTR_ARG, IGNORED_PTR_ARG, NULL, IGNORED_PTR_ARG));
    STRICT_EXPECTED_CALL(HTTPHeaders_Free(IGNORED_PTR_ARG));    //cannot fail
    STRICT_EXPECTED_CALL(STRING_delete(IGNORED_PTR_ARG));       //cannot fail
    STRICT_EXPECTED_CALL(HTTPAPIEX_Destroy(IGNORED_PTR_ARG));   //cannot fail
    STRICT_EXPECTED_CALL(gballoc_free(IGNORED_PTR_ARG));        //cannot fail
}
static int InitializeConnection(PMQTTTRANSPORT_HANDLE_DATA transportState, bool initialConnection)
{
    int result = 0;
    if (!transportState->connected && !transportState->destroyCalled)
    {
        // Construct SAS token
        size_t secSinceEpoch = (size_t)(difftime(get_time(NULL), EPOCH_TIME_T_VALUE) + 0);
        size_t expiryTime = secSinceEpoch + SAS_TOKEN_DEFAULT_LIFETIME;

        // Not checking the success of this variable, if fail it will fail in the SASToken creation and return false;
        STRING_HANDLE emptyKeyName = STRING_new();
        STRING_HANDLE sasToken = SASToken_Create(transportState->device_key, transportState->sasTokenSr, emptyKeyName, expiryTime);
        if (sasToken == NULL)
        {
            result = __LINE__;
        }
        else
        {
            MQTT_CLIENT_OPTIONS options = { 0 };
            options.clientId = (char*)STRING_c_str(transportState->device_id);
            options.willMessage = NULL;
            options.username = (char*)STRING_c_str(transportState->configPassedThroughUsername);
            options.password = (char*)STRING_c_str(sasToken);
            options.keepAliveInterval = DEFAULT_MQTT_KEEPALIVE;
            options.useCleanSession = false;
            options.qualityOfServiceValue = DELIVER_AT_LEAST_ONCE;

            // construct address
            const char* hostAddress = STRING_c_str(transportState->hostAddress);
            const char* hostName = strstr(hostAddress, "//");
            if (hostName == NULL)
            {
                hostName = hostAddress;
            }
            else
            {
                // Increment beyond the double backslash
                hostName += 2;
            }

            transportState->xioTransport = getIoTransportProvider(hostName, transportState->portNum);
            if (mqtt_client_connect(transportState->mqttClient, transportState->xioTransport, &options) != 0)
            {
                LogError("failure connecting to address %s:%d.\r\n", STRING_c_str(transportState->hostAddress), transportState->portNum);
                result = __LINE__;
            }
            else
            {
                transportState->connected = true;
                result = 0;
            }
            STRING_delete(emptyKeyName);
            STRING_delete(sasToken);
        }
    }
    return result;
}
Ejemplo n.º 4
0
const char* IoTHubAccount_GetEventhubAccessKey(void)
{
    char *iothub_connection_string;
    static char access_key[128];

    if ((iothub_connection_string = IoTHubAccount_GetIoTHubConnString()) != NULL)
    {
        STRING_HANDLE iothub_connection_string_str;

        if((iothub_connection_string_str = STRING_construct(iothub_connection_string)) != NULL)
        {
            STRING_TOKENIZER_HANDLE tokenizer;

            if ((tokenizer = STRING_TOKENIZER_create(iothub_connection_string_str)) != NULL)
            {
                STRING_HANDLE tokenString;

                if ((tokenString = STRING_new()) != NULL)
                {
                    STRING_HANDLE valueString;

                    if ((valueString = STRING_new()) != NULL)
                    {
                        while ((STRING_TOKENIZER_get_next_token(tokenizer, tokenString, "=") == 0))
                        {
                            char tokenValue[128];
                            strcpy(tokenValue, STRING_c_str(tokenString));

                            if (STRING_TOKENIZER_get_next_token(tokenizer, tokenString, ";") != 0)
                            {
                                break;
                            }

                            if (strcmp(tokenValue, "SharedAccessKey") == 0)
                            {
                                strcpy(access_key, STRING_c_str(tokenString));
                                break;
                            }
                        }

                        STRING_delete(valueString);
                    }

                    STRING_delete(tokenString);
                }

                STRING_TOKENIZER_destroy(tokenizer);
            }

            STRING_delete(iothub_connection_string_str);
        }
    }

    return access_key;
}
static int connection_setup(OUTPROCESS_HANDLE_DATA* handleData, OUTPROCESS_MODULE_CONFIG * config)
{
	int result;
	handleData->control_socket = -1;
	/*
	* Start with messaging socket.
	*/
	/*Codes_SRS_OUTPROCESS_MODULE_17_008: [ This function shall create a pair socket for sending gateway messages to the module host. ]*/
	handleData->message_socket = nn_socket(AF_SP, NN_PAIR);
	if (handleData->message_socket < 0)
	{
		result = handleData->message_socket;
		LogError("message socket failed to create, result = %d, errno = %d", result, nn_errno());
	}
	else
	{
		/*Codes_SRS_OUTPROCESS_MODULE_17_009: [ This function shall bind and connect the pair socket to the message_uri. ]*/
		int message_bind_id = nn_connect(handleData->message_socket, STRING_c_str(config->message_uri));
		if (message_bind_id < 0)
		{
			result = message_bind_id;
			LogError("remote socket failed to bind to message URL, result = %d, errno = %d", result, nn_errno());
		}
		else
		{
			/*
			* Now, the control socket.
			*/
			/*Codes_SRS_OUTPROCESS_MODULE_17_010: [ This function shall create a request/reply socket for sending control messages to the module host. ]*/
			handleData->control_socket = nn_socket(AF_SP, NN_PAIR);
			if (handleData->control_socket < 0)
			{
				result = handleData->control_socket;
				LogError("remote socket failed to connect to control URL, result = %d, errno = %d", result, nn_errno());
			}
			else
			{
				/*Codes_SRS_OUTPROCESS_MODULE_17_011: [ This function shall connect the request/reply socket to the control_id. ]*/
				int control_connect_id = nn_connect(handleData->control_socket, STRING_c_str(config->control_uri));
				if (control_connect_id < 0)
				{
					result = control_connect_id;
					LogError("remote socket failed to connect to control URL, result = %d, errno = %d", result, nn_errno());
				}
				else
				{
					result = 0;
				}
			}
		}
	}
	return result;
}
Ejemplo n.º 6
0
STRING_HANDLE URL_Encode(STRING_HANDLE input)
{
    STRING_HANDLE result;
    if (input == NULL)
    {
        /*Codes_SRS_URL_ENCODE_06_001: [If input is NULL then URL_Encode will return NULL.]*/
        result = NULL;
        LogError("URL_Encode:: NULL input\r\n");
    }
    else
    {
        size_t lengthOfResult = 0;
        char* encodedURL;
        const char* currentInput;
        unsigned char currentUnsignedChar;
        currentInput = STRING_c_str(input);
        /*Codes_SRS_URL_ENCODE_06_003: [If input is a zero length string then URL_Encode will return a zero length string.]*/
        do
        {
            currentUnsignedChar = (unsigned char)(*currentInput++);
            lengthOfResult += urlEncoding[currentUnsignedChar].numberOfChars;
        } while (currentUnsignedChar != 0);
        if ((encodedURL = malloc(lengthOfResult)) == NULL)
        {
            /*Codes_SRS_URL_ENCODE_06_002: [If an error occurs during the encoding of input then URL_Encode will return NULL.]*/
            result = NULL;
            LogError("URL_Encode:: MALLOC failure on encode.\r\n");
        }
        else
        {
            size_t currentEncodePosition = 0;
            currentInput = STRING_c_str(input);
            do
            {
                currentUnsignedChar = (unsigned char)(*currentInput++);
                if (urlEncoding[currentUnsignedChar].numberOfChars == 1)
                {
                    encodedURL[currentEncodePosition++] = *(urlEncoding[currentUnsignedChar].encoding);
                }
                else
                {
                    memcpy(encodedURL + currentEncodePosition, urlEncoding[currentUnsignedChar].encoding, urlEncoding[currentUnsignedChar].numberOfChars);
                    currentEncodePosition += urlEncoding[currentUnsignedChar].numberOfChars;
                }
            } while (currentUnsignedChar != 0);
            result = STRING_new_with_memory(encodedURL);
        }
    }
    return result;
}
static void on_write_complete(BLEIO_GATT_HANDLE bleio_gatt_handle, void* write_context, BLEIO_GATT_RESULT result)
{
    // this MUST NOT be NULL
    WRITE_CONTEXT* context = (WRITE_CONTEXT*)write_context;
    if (context->handle_data->on_write_complete != NULL)
    {
        if (result != BLEIO_GATT_OK)
        {
            LogError("An error occurred while executing instruction of type %d for characteristic %s",
                context->instruction->instruction_type,
                STRING_c_str(context->instruction->characteristic_uuid)
            );
        }

        /*Codes_SRS_BLEIO_SEQ_13_021: [ When the WRITE_AT_EXIT instruction completes execution this API shall invoke the on_write_complete callback passing in the status of the operation and the callback context that was passed in via the BLEIO_SEQ_INSTRUCTION structure. ]*/
        /*Codes_SRS_BLEIO_SEQ_13_020: [ When the WRITE_AT_INIT instruction completes execution this API shall invoke the on_write_complete callback passing in the status of the operation and the callback context that was passed in via the BLEIO_SEQ_INSTRUCTION structure. ]*/
        /*Codes_SRS_BLEIO_SEQ_13_034: [ When the WRITE_ONCE instruction completes execution this API shall invoke the on_write_complete callback passing in the status of the operation and the callback context that was passed in via the BLEIO_SEQ_INSTRUCTION structure. ]*/
        /*Codes_SRS_BLEIO_SEQ_13_042: [ When a WRITE_ONCE or a WRITE_AT_INIT instruction completes execution this API shall invoke the on_write_complete callback passing in the status of the operation and the callback context that was passed in via the BLEIO_SEQ_INSTRUCTION structure. ]*/
        context->handle_data->on_write_complete(
            (BLEIO_SEQ_HANDLE)context->handle_data,
            context->instruction->context,
            STRING_c_str(context->instruction->characteristic_uuid),
            context->instruction->instruction_type,
            result == BLEIO_GATT_OK ? BLEIO_SEQ_OK : BLEIO_SEQ_ERROR
        );
    }

    /*Codes_SRS_BLEIO_SEQ_13_026: [ When the WRITE_AT_INIT instruction completes execution this API shall free the buffer that was passed in via the instruction. ]*/
    /*Codes_SRS_BLEIO_SEQ_13_041: [ When a WRITE_AT_INIT or a WRITE_ONCE instruction completes execution this API shall free the buffer that was passed in via the instruction. ]*/
    /*Codes_SRS_BLEIO_SEQ_13_027: [ When the WRITE_AT_EXIT instruction completes execution this API shall free the buffer that was passed in via the instruction. ]*/
    /*Codes_SRS_BLEIO_SEQ_13_035: [ When the WRITE_ONCE instruction completes execution this API shall free the buffer that was passed in via the instruction. ]*/
    // free the buffer that was written
    BUFFER_delete(context->instruction->data.buffer);
    context->instruction->data.buffer = NULL;

    // invoke the internal complete callback if we have one
    if (context->on_internal_read_complete != NULL)
    {
        context->on_internal_read_complete(context->handle_data, context->instruction);
    }

    // dec ref the handle data
    // NOTE: The call below MUST occur *after* the BUFFER_delete call above
    // because `dec_ref_handle` might end up destroying the sequence itself
    // at which point context->instruction no longer exists (because it is
    // simply a pointer to the instructions vector in the sequence).
    dec_ref_handle(context->handle_data);

    free(context);
}
 static void setup_dev_auth_emulator_generate_credentials_mocks(const char* token_scope)
 {
     STRICT_EXPECTED_CALL(STRING_new());
     STRICT_EXPECTED_CALL(get_time(IGNORED_PTR_ARG));
     STRICT_EXPECTED_CALL(STRING_construct(token_scope));
     STRICT_EXPECTED_CALL(STRING_construct(IGNORED_PTR_ARG))
         .IgnoreArgument_psz();
     STRICT_EXPECTED_CALL(SASToken_Create(IGNORED_PTR_ARG, IGNORED_PTR_ARG, IGNORED_PTR_ARG, IGNORED_NUM_ARG))
         .IgnoreArgument_scope()
         .IgnoreArgument_keyName()
         .IgnoreArgument_expiry()
         .IgnoreArgument_key();
     STRICT_EXPECTED_CALL(STRING_c_str(IGNORED_PTR_ARG))
         .IgnoreArgument_handle();
     STRICT_EXPECTED_CALL(mallocAndStrcpy_s(IGNORED_PTR_ARG, IGNORED_PTR_ARG))
         .IgnoreArgument_destination()
         .IgnoreArgument_source();
     STRICT_EXPECTED_CALL(STRING_delete(IGNORED_PTR_ARG))
         .IgnoreArgument_handle();
     STRICT_EXPECTED_CALL(STRING_delete(IGNORED_PTR_ARG))
         .IgnoreArgument_handle();
     STRICT_EXPECTED_CALL(STRING_delete(IGNORED_PTR_ARG))
         .IgnoreArgument_handle();
     STRICT_EXPECTED_CALL(STRING_delete(IGNORED_PTR_ARG))
         .IgnoreArgument_handle();
 }
STRING_TOKENIZER_HANDLE STRING_TOKENIZER_create(STRING_HANDLE handle)
{
    STRING_TOKEN *result;
    char* inputStringToMalloc;

    /* Codes_SRS_STRING_04_001: [STRING_TOKENIZER_create shall return an NULL STRING_TOKENIZER_HANDLE if parameter handle is NULL] */
    if (handle == NULL)
    {
        LogError("Invalid Argument. Handle cannot be NULL.\r\n");
        result = NULL;
    }
    /* Codes_SRS_STRING_04_002: [STRING_TOKENIZER_create shall allocate a new STRING_TOKENIZER_HANDLE having the content of the STRING_HANDLE copied and current position pointing at the beginning of the string] */
    else if((result = (STRING_TOKEN *)malloc(sizeof(STRING_TOKEN))) == NULL)
    {
        LogError("Memory Allocation failed. Cannot allocate STRING_TOKENIZER.\r\n");
    }
    else if ((mallocAndStrcpy_s(&inputStringToMalloc, STRING_c_str(handle))) != 0)
    {
        LogError("Memory Allocation Failed. Cannot allocate and copy string Content.\r\n");
        free(result);
        result = NULL;
    }
    else
    {
        result->inputString = inputStringToMalloc;
        result->currentPos = result->inputString; //Current Pos will point to the initial position of Token.
        result->sizeOfinputString = strlen(result->inputString); //Calculate Size of Current String
    }
    
    return (STRING_TOKENIZER_HANDLE)result;
}
static int prov_sc_get_record(PROVISIONING_SERVICE_CLIENT_HANDLE prov_client, const char* id, void** handle_ptr, HANDLE_FUNCTION_VECTOR vector, const char* path_format)
{
    int result = 0;

    if (prov_client == NULL)
    {
        LogError("Invalid Provisioning Client Handle");
        result = __FAILURE__;
    }
    else if (id == NULL)
    {
        LogError("Invalid id");
        result = __FAILURE__;
    }
    else if (handle_ptr == NULL)
    {
        LogError("Invalid handle");
        result = __FAILURE__;
    }
    else
    {
        STRING_HANDLE registration_path = create_registration_path(path_format, id);
        if (registration_path == NULL)
        {
            LogError("Failed to construct a registration path");
            result = __FAILURE__;
        }
        else
        {
            HTTP_HEADERS_HANDLE request_headers;
            if ((request_headers = construct_http_headers(prov_client, NULL, HTTP_CLIENT_REQUEST_GET)) == NULL)
            {
                LogError("Failure constructing http headers");
                result = __FAILURE__;
            }
            else
            {
                result = rest_call(prov_client, HTTP_CLIENT_REQUEST_GET, STRING_c_str(registration_path), request_headers, NULL);

                if (result == 0)
                {
                    void* handle;
                    if ((handle = vector.deserializeFromJson(prov_client->response)) == NULL)
                    {
                        LogError("Failure constructing new enrollment structure from json response");
                        result = __FAILURE__;
                    }
                    *handle_ptr = handle;
                }
                clear_response(prov_client);
            }
            HTTPHeaders_Free(request_headers);
        }
        STRING_delete(registration_path);
    }

    return result;
}
static void show_platform_info()
{
    STRING_HANDLE platform_info = platform_get_platform_info();
    if (platform_info != NULL)
    {
        (void)printf("%s\r\n", STRING_c_str(platform_info));
        STRING_delete(platform_info);
    }
}
BLEIO_SEQ_RESULT schedule_write(
    BLEIO_SEQ_HANDLE_DATA* handle_data,
    BLEIO_SEQ_INSTRUCTION* instruction,
    ON_INTERNAL_IO_COMPLETE on_internal_read_complete
)
{
    BLEIO_SEQ_RESULT result;
    WRITE_CONTEXT* context = (WRITE_CONTEXT*)malloc(sizeof(WRITE_CONTEXT));

    /*Codes_SRS_BLEIO_SEQ_13_014: [ BLEIO_Seq_Run shall return BLEIO_SEQ_ERROR if an underlying platform call fails. ]*/
    if (context == NULL)
    {
        LogError("malloc failed");
        result = BLEIO_SEQ_ERROR;
    }
    else
    {
        context->handle_data = handle_data;
        context->instruction = instruction;
        context->on_internal_read_complete = on_internal_read_complete;

        const unsigned char* buffer = BUFFER_u_char(instruction->data.buffer);
        size_t buffer_size = BUFFER_length(instruction->data.buffer);

        // add ref to the handle data object since we now will have an
        // outstanding I/O operation; the reason why we increment the
        // reference here as opposed to when we know that BLEIO_gatt_read_char_by_uuid
        // was successful is because the operation could potentially complete
        // even before we hit the if check after this call and 'on_read_complete'
        // might have run by then in which case it would have done a DEC_REF and
        // the ref counts will be out of whack
        INC_REF(BLEIO_SEQ_HANDLE_DATA, handle_data);

        int write_result = BLEIO_gatt_write_char_by_uuid(
            handle_data->bleio_gatt_handle,
            STRING_c_str(instruction->characteristic_uuid),
            buffer,
            buffer_size,
            on_write_complete,
            context
        );
        if (write_result != 0)
        {
            /*Codes_SRS_BLEIO_SEQ_13_014: [ BLEIO_Seq_Run shall return BLEIO_SEQ_ERROR if an underlying platform call fails. ]*/
            result = BLEIO_SEQ_ERROR;
            free(context);
            DEC_REF(BLEIO_SEQ_HANDLE_DATA, handle_data);
            LogError("BLEIO_gatt_write_char_by_uuid failed with %d.", write_result);
        }
        else
        {
            result = BLEIO_SEQ_OK;
        }
    }

    return result;
}
static STRING_HANDLE create_devices_path(STRING_HANDLE iothub_host_fqdn, const char* device_id)
{
    STRING_HANDLE devices_path;
    if ((devices_path = STRING_construct_sprintf(IOTHUB_DEVICES_PATH_FMT, STRING_c_str(iothub_host_fqdn), device_id)) == NULL)
    {
        LogError("Failed creating devices_path (STRING_new failed)");
    }
    return devices_path;
}
Ejemplo n.º 14
0
/*returns 0 if success, otherwise __LINE__*/
static int stop_module(int publish_socket, BROKER_MODULEINFO* module_info)
{
    int  quit_result, close_result, thread_result, result;

    /*Codes_SRS_BROKER_17_021: [ This function shall send a quit signal to the worker thread by sending BROKER_MODULEINFO::quit_message_guid to the publish_socket. ]*/
    /* send the unique quite id for this module */
    if ((quit_result = nn_send(publish_socket, STRING_c_str(module_info->quit_message_guid), BROKER_GUID_SIZE, 0)) < 0)
    {
        /*Codes_SRS_BROKER_17_015: [ This function shall close the BROKER_MODULEINFO::receive_socket. ]*/
        /* at the cost of a data race, we will close the socket to terminate the thread */
        nn_close(module_info->receive_socket);
        LogError("unable to peacefully close thread for module [%p], nn_send error [%d], taking harsher methods", module_info, quit_result);
    }
    else
    {
        /*Codes_SRS_BROKER_02_001: [ Broker_RemoveModule shall lock BROKER_MODULEINFO::socket_lock. ]*/
        if (Lock(module_info->socket_lock) != LOCK_OK)
        {
            /*Codes_SRS_BROKER_17_015: [ This function shall close the BROKER_MODULEINFO::receive_socket. ]*/
            /* at the cost of a data race, we will close the socket to terminate the thread */
            nn_close(module_info->receive_socket);
            LogError("unable to peacefully close thread for module [%p], Lock error, taking harsher methods", module_info );
        }
        else
        {
            /*Codes_SRS_BROKER_17_015: [ This function shall close the BROKER_MODULEINFO::receive_socket. ]*/
            close_result = nn_close(module_info->receive_socket);
            if (close_result < 0)
            {
                LogError("Receive socket close failed for module at  item [%p] failed", module_info);
            }
            else
            {
                /*all is fine, thread will eventually stop and be joined*/
            }
            /*Codes_SRS_BROKER_02_003: [ After closing the socket, Broker_RemoveModule shall unlock BROKER_MODULEINFO::info_lock. ]*/
            if (Unlock(module_info->socket_lock) != LOCK_OK)
            {
                LogError("unable to unlock socket lock");
            }
        }
    }
    /*Codes_SRS_BROKER_13_104: [The function shall wait for the module's thread to exit by joining BROKER_MODULEINFO::thread via ThreadAPI_Join. ]*/
    if (ThreadAPI_Join(module_info->thread, &thread_result) != THREADAPI_OK)
    {
        result = __LINE__;
        LogError("ThreadAPI_Join() returned an error.");
    }
    else
    {
        result = 0;
    }
    return result;
}
IOTHUB_DEVICE_HANDLE IoTHubTransportMqtt_Register(TRANSPORT_HANDLE handle, const char* deviceId, const char* deviceKey, IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle, PDLIST_ENTRY waitingToSend)
{
    IOTHUB_DEVICE_HANDLE result;
    // Codes_SRS_IOTHUB_MQTT_TRANSPORT_17_001: [ IoTHubTransportMqtt_Register shall return NULL if the TRANSPORT_HANDLE is NULL.]
    // Codes_SRS_IOTHUB_MQTT_TRANSPORT_17_002: [ IoTHubTransportMqtt_Register shall return NULL if deviceId, deviceKey or waitingToSend are NULL.]
    if ((handle == NULL) || (deviceId == NULL) || (deviceKey == NULL) || (waitingToSend == NULL))
    {
        result = NULL;
    }
    else
    {
        MQTTTRANSPORT_HANDLE_DATA* transportState = (MQTTTRANSPORT_HANDLE_DATA*)handle;

        // Codes_SRS_IOTHUB_MQTT_TRANSPORT_17_003: [ IoTHubTransportMqtt_Register shall return NULL if deviceId or deviceKey do not match the deviceId and deviceKey passed in during IoTHubTransportMqtt_Create.]
        if (strcmp(STRING_c_str(transportState->device_id), deviceId) != 0)
        {
            result = NULL;
        }
        else if (strcmp(STRING_c_str(transportState->device_key), deviceKey) != 0)
        {
            result = NULL;
        }
        else
        {
            if (transportState->isRegistered == true)
            {
                LogError("Transport already has device registered by id: [%s]", deviceId);
                result = NULL;
            }
            else
            {
                transportState->isRegistered = true;
                // Codes_SRS_IOTHUB_MQTT_TRANSPORT_17_004: [ IoTHubTransportMqtt_Register shall return the TRANSPORT_HANDLE as the IOTHUB_DEVICE_HANDLE. ]
                result = (IOTHUB_DEVICE_HANDLE)handle;
            }

        }
    }

    return result;
}
void IoTHubTransportMqtt_Unsubscribe(TRANSPORT_HANDLE handle)
{
    PMQTTTRANSPORT_HANDLE_DATA transportState = (PMQTTTRANSPORT_HANDLE_DATA)handle;
    /* Codes_SRS_IOTHUB_MQTT_TRANSPORT_07_019: [If parameter handle is NULL then IoTHubTransportMqtt_Unsubscribe shall do nothing.] */
    if (transportState != NULL && transportState->subscribed)
    {
        /* Codes_SRS_IOTHUB_MQTT_TRANSPORT_07_020: [IoTHubTransportMqtt_Unsubscribe shall call mqtt_client_unsubscribe to unsubscribe the mqtt message topic.] */
        const char* unsubscribe[] = { STRING_c_str(transportState->mqttMessageTopic) };
        (void)mqtt_client_unsubscribe(transportState->mqttClient, transportState->packetId++, unsubscribe, 1);
        transportState->subscribed = false;
    }
}
Ejemplo n.º 17
0
static void PrintProperties(MAP_HANDLE map)
{
    STRING_HANDLE jsonKVP = Map_ToJSON(map);
    if (jsonKVP != NULL)
    {
        (void)printf("   >>>Key Value Pairs Received:[%s]\r\n", STRING_c_str(jsonKVP));
        STRING_delete(jsonKVP);
    }
    else
    {
        (void)printf("   >>>Key Value Pairs Received:[]\r\n");
    }
}
Ejemplo n.º 18
0
const char* IoTHubAccount_GetSharedAccessSignature(IOTHUB_ACCOUNT_INFO_HANDLE acctHandle)
{
    const char* result = NULL;
    IOTHUB_ACCOUNT_INFO* acctInfo = (IOTHUB_ACCOUNT_INFO*)acctHandle;
    if (acctInfo != NULL)
    {
        if (acctInfo->sharedAccessToken != NULL)
        {
            // Reuse the sharedAccessToken if it's been created already
            result = acctInfo->sharedAccessToken;
        }
        else
        {
        time_t currentTime = time(NULL);
        size_t expiry_time = (size_t)(currentTime + 3600);

        STRING_HANDLE accessKey = STRING_construct(acctInfo->sharedAccessKey);
        STRING_HANDLE iotName = STRING_construct(acctInfo->hostname);
        STRING_HANDLE keyName = STRING_construct(acctInfo->keyName);
        if (accessKey != NULL && iotName != NULL && keyName != NULL)
        {
            STRING_HANDLE sasHandle = SASToken_Create(accessKey, iotName, keyName, expiry_time);
            if (sasHandle == NULL)
            {

                result = NULL;
            }
            else
            {
                if (mallocAndStrcpy_s(&acctInfo->sharedAccessToken, STRING_c_str(sasHandle)) != 0)
                {
                    result = NULL;
                }
                else
                {
                    result = acctInfo->sharedAccessToken;
                }
                STRING_delete(sasHandle);
            }
        }
        STRING_delete(accessKey);
        STRING_delete(iotName);
        STRING_delete(keyName);
    }
    }
    else
    {
        result = NULL;
    }
    return result; 
}
static DYNAMIC_LIBRARY_HANDLE NodeModuleLoader_LoadBindingModule(const MODULE_LOADER* loader)
{
    // find the binding path from the loader configuration; if there isn't one, use
    // a default path
    const char* binding_path = NODE_BINDING_MODULE_NAME;
    if (loader->configuration != NULL && loader->configuration->binding_path != NULL)
    {
        //Codes_SRS_NODE_MODULE_LOADER_13_032: [ NodeModuleLoader_Load shall use the the binding module path given in loader->configuration->binding_path if loader->configuration is not NULL. ]
        binding_path = STRING_c_str(loader->configuration->binding_path);
    }

    //Codes_SRS_NODE_MODULE_LOADER_13_004 : [NodeModuleLoader_Load shall load the binding module library into memory by calling DynamicLibrary_LoadLibrary.]
    return DynamicLibrary_LoadLibrary(binding_path);
}
Ejemplo n.º 20
0
static void parseResponseJsonExpectedCalls()
{
    STRICT_EXPECTED_CALL(BUFFER_u_char(IGNORED_PTR_ARG));
    STRICT_EXPECTED_CALL(BUFFER_length(IGNORED_PTR_ARG)).CallCannotFail();       //cannot fail (returns length 0)
    STRICT_EXPECTED_CALL(STRING_from_byte_array(IGNORED_PTR_ARG, IGNORED_NUM_ARG));
    STRICT_EXPECTED_CALL(STRING_c_str(IGNORED_PTR_ARG));
    STRICT_EXPECTED_CALL(json_parse_string(IGNORED_PTR_ARG));
    STRICT_EXPECTED_CALL(json_value_get_object(IGNORED_PTR_ARG));
    STRICT_EXPECTED_CALL(json_object_get_value(IGNORED_PTR_ARG, IGNORED_PTR_ARG));
    STRICT_EXPECTED_CALL(json_object_get_value(IGNORED_PTR_ARG, IGNORED_PTR_ARG));
    STRICT_EXPECTED_CALL(json_serialize_to_string(IGNORED_PTR_ARG));
    STRICT_EXPECTED_CALL(json_value_get_number(IGNORED_PTR_ARG)).CallCannotFail();   //cannot fail (returns -1, which isn't strictly failure)
    STRICT_EXPECTED_CALL(STRING_delete(IGNORED_PTR_ARG));           //cannot fail
    STRICT_EXPECTED_CALL(json_value_free(IGNORED_PTR_ARG));         //cannot fail
}
int connectionstringparser_splitHostName(STRING_HANDLE hostNameString, STRING_HANDLE nameString, STRING_HANDLE suffixString)
{
    int result;

    if (hostNameString == NULL)
    {
        /* Codes_SRS_CONNECTIONSTRINGPARSER_21_034: [If the hostNameString is NULL, connectionstringparser_splitHostName shall return __FAILURE__.]*/
        result = __FAILURE__;
    }
    else
    {
        /* Codes_SRS_CONNECTIONSTRINGPARSER_21_033: [connectionstringparser_splitHostName shall convert the hostNameString to a connection_string passed in as argument, and call connectionstringparser_splitHostName_from_char.]*/
        result = connectionstringparser_splitHostName_from_char(STRING_c_str(hostNameString), nameString, suffixString);
    }

    return result;
}
STRING_TOKENIZER_HANDLE STRING_TOKENIZER_create(STRING_HANDLE handle)
{
    STRING_TOKENIZER_HANDLE result;

    /* Codes_SRS_STRING_04_001: [STRING_TOKENIZER_create shall return an NULL STRING_TOKENIZER_HANDLE if parameter handle is NULL] */
    if (handle == NULL)
    {
        LogError("Invalid Argument. Handle cannot be NULL.");
        result = NULL;
    }
    else
    {
        /* Codes_SRS_STRING_04_002: [STRING_TOKENIZER_create shall allocate a new STRING_TOKENIZER_HANDLE having the content of the STRING_HANDLE copied and current position pointing at the beginning of the string] */
        result = STRING_TOKENIZER_create_from_char(STRING_c_str(handle));
    }

    return result;
}
Ejemplo n.º 23
0
/*this function "links" IoTHub to the serialization library*/
static IOTHUBMESSAGE_DISPOSITION_RESULT IoTHubMessage(IOTHUB_MESSAGE_HANDLE message, void* userContextCallback)
{
    const unsigned char* buffer;
    size_t size;
    if (IoTHubMessage_GetByteArray(message, &buffer, &size) != IOTHUB_MESSAGE_OK)
    {
        ASSERT_FAIL("unable to IoTHubMessage_GetByteArray");
    }
    else
    {
        /*buffer is not zero terminated*/
        STRING_HANDLE temp = STRING_construct_n((char*)buffer, size);
        ASSERT_IS_NOT_NULL(temp);
        EXECUTE_COMMAND(userContextCallback, STRING_c_str(temp));
        STRING_delete(temp);
    }
    return IOTHUBMESSAGE_ACCEPTED;
}
static int prov_sc_delete_record_by_param(PROVISIONING_SERVICE_CLIENT_HANDLE prov_client, const char* id, const char* etag, const char* path_format)
{
    int result = 0;

    if (prov_client == NULL)
    {
        LogError("Invalid Provisioning Client Handle");
        result = __FAILURE__;
    }
    else if (id == NULL)
    {
        LogError("Invalid Id");
        result = __FAILURE__;
    }
    else
    {
        STRING_HANDLE registration_path = create_registration_path(path_format, id);
        if (registration_path == NULL)
        {
            LogError("Failed to construct a registration path");
            result = __FAILURE__;
        }
        else
        {
            HTTP_HEADERS_HANDLE request_headers;
            if ((request_headers = construct_http_headers(prov_client, etag, HTTP_CLIENT_REQUEST_DELETE)) == NULL)
            {
                LogError("Failure constructing http headers");
                result = __FAILURE__;
            }
            else
            {
                result = rest_call(prov_client, HTTP_CLIENT_REQUEST_DELETE, STRING_c_str(registration_path), request_headers, NULL);
                clear_response(prov_client);
            }
            HTTPHeaders_Free(request_headers);
        }
        STRING_delete(registration_path);
    }

    return result;
}
static int put_SAS_token_to_cbs(AUTHENTICATION_INSTANCE* instance, STRING_HANDLE cbs_audience, char* sas_token)
{
    int result;

    // Codes_SRS_IOTHUBTRANSPORT_AMQP_AUTH_09_043: [authentication_do_work() shall set `instance->is_cbs_put_token_in_progress` to TRUE]
    // Codes_SRS_IOTHUBTRANSPORT_AMQP_AUTH_09_057: [authentication_do_work() shall set `instance->is_cbs_put_token_in_progress` to TRUE]
    // Codes_SRS_IOTHUBTRANSPORT_AMQP_AUTH_09_075: [authentication_do_work() shall set `instance->is_cbs_put_token_in_progress` to TRUE]
    instance->is_cbs_put_token_in_progress = true;

    // Codes_SRS_IOTHUBTRANSPORT_AMQP_AUTH_09_046: [The SAS token provided shall be sent to CBS using cbs_put_token(), using `servicebus.windows.net:sastoken` as token type, `devices_path` as audience and passing on_cbs_put_token_complete_callback]
    // Codes_SRS_IOTHUBTRANSPORT_AMQP_AUTH_09_058: [The SAS token shall be sent to CBS using cbs_put_token(), using `servicebus.windows.net:sastoken` as token type, `devices_path` as audience and passing on_cbs_put_token_complete_callback]
    // Codes_SRS_IOTHUBTRANSPORT_AMQP_AUTH_09_076: [The SAS token shall be sent to CBS using cbs_put_token(), using `servicebus.windows.net:sastoken` as token type, `devices_path` as audience and passing on_cbs_put_token_complete_callback]
    const char* cbs_audience_c_str = STRING_c_str(cbs_audience);
    if (cbs_put_token_async(instance->cbs_handle, SAS_TOKEN_TYPE, cbs_audience_c_str, sas_token, on_cbs_put_token_complete_callback, instance) != RESULT_OK)
    {
        // Codes_SRS_IOTHUBTRANSPORT_AMQP_AUTH_09_048: [If cbs_put_token() failed, authentication_do_work() shall set `instance->is_cbs_put_token_in_progress` to FALSE, destroy `devices_path` and return]
        // Codes_SRS_IOTHUBTRANSPORT_AMQP_AUTH_09_060: [If cbs_put_token() fails, `instance->is_cbs_put_token_in_progress` shall be set to FALSE]
        // Codes_SRS_IOTHUBTRANSPORT_AMQP_AUTH_09_078: [If cbs_put_token() fails, `instance->is_cbs_put_token_in_progress` shall be set to FALSE]
        instance->is_cbs_put_token_in_progress = false;
        result = __FAILURE__;
        LogError("Failed putting SAS token to CBS for device '%s' (cbs_put_token failed)", instance->device_id);
    }
    else
    {
        // Codes_SRS_IOTHUBTRANSPORT_AMQP_AUTH_09_047: [If cbs_put_token() succeeds, authentication_do_work() shall set `instance->current_sas_token_put_time` with current time]
        // Codes_SRS_IOTHUBTRANSPORT_AMQP_AUTH_09_059: [If cbs_put_token() succeeds, authentication_do_work() shall set `instance->current_sas_token_put_time` with current time]
        // Codes_SRS_IOTHUBTRANSPORT_AMQP_AUTH_09_077: [If cbs_put_token() succeeds, authentication_do_work() shall set `instance->current_sas_token_put_time` with the current time]
        time_t current_time;

        if ((current_time = get_time(NULL)) == INDEFINITE_TIME)
        {
            LogError("Failed setting current_sas_token_put_time for device '%s' (get_time() failed)", instance->device_id);
        }

        instance->current_sas_token_put_time = current_time; // If it failed, fear not. `current_sas_token_put_time` shall be checked for INDEFINITE_TIME wherever it is used.

        result = RESULT_OK;
    }

    return result;
}
Ejemplo n.º 26
0
char* secure_dev_tpm_get_storage_key(SEC_DEVICE_HANDLE handle)
{
    char* result;
    if (handle == NULL)
    {
        /* Codes_SRS_SECURE_DEVICE_TPM_07_016: [ If handle is NULL, secure_dev_tpm_get_storage_key shall return NULL. ] */
        LogError("Invalid handle value specified");
        result = NULL;
    }
    else if (handle->srk_pub.publicArea.unique.rsa.t.size == 0)
    {
        /* Codes_SRS_SECURE_DEVICE_TPM_07_017: [ If the srk_public value was not initialized, secure_dev_tpm_get_storage_key shall return NULL. ] */
        LogError("storage root key is invalid");
        result = NULL;
    }
    else
    {
        unsigned char data_bytes[1024];
        unsigned char* data_pos = data_bytes;
        /* Codes_SRS_SECURE_DEVICE_TPM_07_018: [ secure_dev_tpm_get_storage_key shall allocate and return the Storage Root Key. ] */
        uint32_t data_length = TPM2B_PUBLIC_Marshal(&handle->srk_pub, &data_pos, NULL);
        STRING_HANDLE encoded_srk = Azure_Base64_Encode_Bytes(data_bytes, data_length);
        if (encoded_srk == NULL)
        {
            /* Codes_SRS_SECURE_DEVICE_TPM_07_019: [ If any failure is encountered, secure_dev_tpm_get_storage_key shall return NULL. ] */
            LogError("Failure encoding storage root key");
            result = NULL;
        }
        else
        {
            if (mallocAndStrcpy_s(&result, STRING_c_str(encoded_srk)) != 0)
            {
                /* Codes_SRS_SECURE_DEVICE_TPM_07_019: [ If any failure is encountered, secure_dev_tpm_get_storage_key shall return NULL. ] */
                LogError("Failure allocating storage root key");
                result = NULL;
            }
            STRING_delete(encoded_srk);
        }
    }
    return result;
}
    static void setup_dev_auth_emulator_create_mocks(bool use_persist_file)
    {
        STRICT_EXPECTED_CALL(gballoc_malloc(IGNORED_NUM_ARG))
            .IgnoreArgument_size();
        STRICT_EXPECTED_CALL(STRING_c_str(IGNORED_PTR_ARG))
            .IgnoreArgument_handle();

        if (use_persist_file)
        {
            setup_retrieve_persisted_key_mocks(true);
        }
        else
        {
            setup_retrieve_persisted_key_mocks(false);
            setup_generate_key_mocks();
            setup_persisted_keys_info_mocks();
        }

        STRICT_EXPECTED_CALL(json_value_free(IGNORED_PTR_ARG))
            .IgnoreArgument_value();
    }
Ejemplo n.º 28
0
static void connectionLost(void *context, char *cause)
{
	PMQTTTAPI_HANDLE_DATA transportState = (PMQTTTAPI_HANDLE_DATA)context;
	LogError("Lost Connection, reseting Connection State. Cause: %s \r\n", cause);

	if (transportState != NULL)
	{
		transportState->connected = false;
	}

	LogInfo("Trying to connect again\r\n");

	if (!checkAndTryToConnect(transportState))
	{
		LogError("Could not connect again. \r\n");
	}
	else
	{
		LogInfo("Connected.\r\n");
		if (transportState->subscribed)
		{
			int rc;
			LogInfo("Trying to Subscribe after reconnect.\r\n");

			if ((rc = MQTTClient_subscribe(transportState->client, STRING_c_str(transportState->subscribedTopicHandleData->topicName), SUBSCRIBEQOS)) != MQTTCLIENT_SUCCESS)
			{
				LogError("Could not subscribe again. Won't be able to receive messages. Error Code: %d.\r\n", rc);
			}
			else
			{
				LogInfo("Subscribed succesfully after reconnect..\r\n");
			}
		}
	}

	if (cause != NULL)
	{
		MQTTClient_free(cause);
	}
}
Ejemplo n.º 29
0
void MQTTAPI_Unsubscribe(MQTTAPI_TOPIC_HANDLE topicInstance)
{
	/* Codes_SRS_MQTTAPI_04_034: [If topicInstance is NULL MQTTAPI_Unsubscribe shall do nothing.] */
	if (topicInstance != NULL)
	{
		PMQTTAPI_TOPIC_HANDLE_DATA topicHandleData = topicInstance;
		PMQTTTAPI_HANDLE_DATA mqttApiInstance = topicHandleData->mqttApiInstance;

		/* Codes_SRS_MQTTAPI_04_035: [MQTTAPI_Unsubscribe shall call underlying library methods to unsubscribe to the topic Instance.] */
		if (MQTTClient_unsubscribe(mqttApiInstance->client, STRING_c_str(topicHandleData->topicName)) != MQTTCLIENT_SUCCESS)
		{
			LogError("Problems on Unsubscribing to Commands.\r\n");
		}
		else
{
			mqttApiInstance->subscribed = false;
			/* Codes_SRS_MQTTAPI_04_060: [MQTTAPI_Unsubscribe shall release all previously allocated resources pointed by topicInstance.] */
			STRING_delete(mqttApiInstance->subscribedTopicHandleData->topicName);
			free(mqttApiInstance->subscribedTopicHandleData);
		}
	}
}
static int SubscribeToMqttProtocol(PMQTTTRANSPORT_HANDLE_DATA transportState)
{
    int result;

    SUBSCRIBE_PAYLOAD subscribe[] = {
        { STRING_c_str(transportState->mqttMessageTopic), DELIVER_AT_LEAST_ONCE }
    };
    /* Codes_SRS_IOTHUB_MQTT_TRANSPORT_07_016: [IoTHubTransportMqtt_Subscribe shall call mqtt_client_subscribe to subscribe to the Message Topic.] */
    if (mqtt_client_subscribe(transportState->mqttClient, transportState->packetId++, subscribe, 1) != 0)
    {
        /* Codes_SRS_IOTHUB_MQTT_TRANSPORT_07_017: [Upon failure IoTHubTransportMqtt_Subscribe shall return a non-zero value.] */
        result = __LINE__;
    }
    else
    {
        /* Codes_SRS_IOTHUB_MQTT_TRANSPORT_07_018: [On success IoTHubTransportMqtt_Subscribe shall return 0.] */
        transportState->subscribed = true;
        transportState->currPacketState = SUBSCRIBE_TYPE;
        result = 0;
    }
    return result;
}