Esempio n. 1
0
static void CAInitializePipe()
{
    caglobals.ip.selectTimeout = -1;
#ifdef HAVE_PIPE2
    int ret = pipe2(caglobals.ip.shutdownFds, O_CLOEXEC);
#else
    int ret = pipe(caglobals.ip.shutdownFds);
    if (-1 != ret)
    {
        ret = fcntl(caglobals.ip.shutdownFds[0], F_GETFD);
        if (-1 != ret)
        {
            ret = fcntl(caglobals.ip.shutdownFds[0], F_SETFD, ret|FD_CLOEXEC);
        }
        if (-1 != ret)
        {
            ret = fcntl(caglobals.ip.shutdownFds[1], F_GETFD);
        }
        if (-1 != ret)
        {
            ret = fcntl(caglobals.ip.shutdownFds[1], F_SETFD, ret|FD_CLOEXEC);
        }
        if (-1 == ret)
        {
            close(caglobals.ip.shutdownFds[1]);
            close(caglobals.ip.shutdownFds[0]);
            caglobals.ip.shutdownFds[0] = -1;
            caglobals.ip.shutdownFds[1] = -1;
        }
    }
#endif
    if (-1 == ret)
    {
        OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
        caglobals.ip.selectTimeout = SELECT_TIMEOUT; //poll needed for shutdown
    }
}
Esempio n. 2
0
void CAEDRNativeRemoveDevice(const char *remoteAddress)
{
    OIC_LOG(DEBUG, TAG, "CAEDRNativeRemoveDeviceforStateList");

    if (!g_deviceStateList)
    {
        OIC_LOG(ERROR, TAG, "[EDR][Native] gdeviceStateList is null");
        return;
    }
    if (!remoteAddress)
    {
        OIC_LOG(ERROR, TAG, "[EDR][Native] remoteAddress is null");
        return;
    }

    jint index;
    jint length = u_arraylist_length(g_deviceStateList);
    for (index = 0; index < length; index++)
    {
        state_t* state = (state_t*) u_arraylist_get(g_deviceStateList, index);
        if (!state)
        {
            OIC_LOG(DEBUG, TAG, "[EDR][Native] state_t object is null");
            continue;
        }

        if (!strcmp((const char*) state->address, remoteAddress))
        {
            OIC_LOG_V(DEBUG, TAG, "[EDR][Native] remove state : %s", remoteAddress);
            OICFree(state);

            u_arraylist_remove(g_deviceStateList, index);
            break;
        }
    }
    return;
}
Esempio n. 3
0
bool CALEIsBondedDevice(JNIEnv *env, jobject bluetoothDevice)
{
    VERIFY_NON_NULL_RET(env, TAG, "env is null", false);
    VERIFY_NON_NULL_RET(bluetoothDevice, TAG, "bluetoothDevice is null", false);

    jclass jni_cid_device_list = (*env)->FindClass(env, "android/bluetooth/BluetoothDevice");
    if (!jni_cid_device_list)
    {
        OIC_LOG(ERROR, TAG, "jni_cid_device_list is null");
        return false;
    }

    jmethodID jni_mid_getBondState = (*env)->GetMethodID(env, jni_cid_device_list, "getBondState",
                                                         "()I");
    if (!jni_mid_getBondState)
    {
        OIC_LOG(ERROR, TAG, "jni_mid_getBondState is null");
        return false;
    }

    jint jni_bondState = (jint)(*env)->CallIntMethod(env, bluetoothDevice, jni_mid_getBondState);

    OIC_LOG_V(DEBUG, TAG, "bond state is %d", jni_bondState);

    if (BOND_BONDED == jni_bondState)
    {
        OIC_LOG(DEBUG, TAG, "remote device is bonded");
        return true;
    }
    else
    {
        OIC_LOG(DEBUG, TAG, "remote device is not bonded");
        return false;
    }

    return false;
}
Esempio n. 4
0
CAResult_t CAEDRStartNetworkMonitor()
{
    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");

    g_mainloop = g_main_loop_new(NULL, 0);
    if(!g_mainloop)
    {
        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "g_main_loop_new failed\n");
        return CA_STATUS_FAILED;
    }

    if (CA_STATUS_OK != ca_thread_pool_add_task(g_threadPoolHandle, GMainLoopThread, (void *) NULL))
    {
        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to create thread!");
        return CA_STATUS_FAILED;
    }

    // Initialize Bluetooth service
    int err = bt_initialize();
    if (BT_ERROR_NONE != err)
    {
        OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Bluetooth initialization failed!, error num [%x]",
                  err);
        return CA_STATUS_FAILED;
    }

    int ret = bt_adapter_set_state_changed_cb(CAEDRAdapterStateChangeCallback, NULL);
    if(BT_ERROR_NONE != ret)
    {
       OIC_LOG(ERROR, EDR_ADAPTER_TAG, "bt_adapter_set_state_changed_cb failed");
       return CA_STATUS_FAILED;
    }

    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
    return CA_STATUS_OK;
}
Esempio n. 5
0
OCStackResult DiscoverAmsService(PEContext_t *context)
{
    OIC_LOG(INFO, TAG, "IN DiscoverAmsService");

    OCStackResult ret = OC_STACK_ERROR;
    const char DOXM_DEVICEID_QUERY_FMT[] = "%s?%s=%s";
    char uri[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {};
    OCCallbackData cbData = {.context=NULL};
    char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(((OicUuid_t*)0)->id)) + 1] = {};
    uint32_t outLen = 0;
    B64Result b64Ret;

    VERIFY_NON_NULL(TAG, context, ERROR);
    b64Ret = b64Encode(context->amsMgrContext->amsDeviceId.id,
          sizeof(context->amsMgrContext->amsDeviceId.id), base64Buff, sizeof(base64Buff), &outLen);
    VERIFY_SUCCESS(TAG, B64_OK == b64Ret, ERROR);
    snprintf(uri, sizeof(uri), DOXM_DEVICEID_QUERY_FMT, OIC_RSRC_DOXM_URI,
                                       OIC_JSON_DEVICE_ID_NAME, base64Buff);

    cbData.cb = &AmsMgrDiscoveryCallback;
    cbData.context = (void*)context;

    /* TODO
     * If no good response was received for this discovery request,
     * PE would be blocked forever waiting for AMS service to respond with the ACE.
     * Need logic to reset the PE state and send ACCESS_DENIED response,
     * when discovery response from AMS service is not received within certain time.
     */
    OIC_LOG_V(INFO, TAG,"AMS Manager Sending Multicast Discovery with URI = %s", uri);
    ret = OCDoResource(NULL, OC_REST_DISCOVER, uri, NULL, NULL,
                       CT_DEFAULT, OC_LOW_QOS, &cbData, NULL, 0);

exit:
    OIC_LOG(INFO, TAG, "Leaving DiscoverAmsService");
    return ret;
}
Esempio n. 6
0
CAResult_t CAEDRStartServiceSearch(const char *remoteAddress)
{
    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");

    // Input validation
    VERIFY_NON_NULL(remoteAddress, EDR_ADAPTER_TAG, "Remote address is null");
    if (!remoteAddress[0])
    {
        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Remote address is empty!");
        return CA_STATUS_INVALID_PARAM;
    }

    bt_error_e err = bt_device_start_service_search(remoteAddress);
    // Start searching for OIC service
    if (BT_ERROR_NONE != err)
    {
        OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Get bonded device failed!, error num [%x]",
                  err);
        return CA_STATUS_FAILED;
    }

    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
    return CA_STATUS_OK;
}
Esempio n. 7
0
/**
 * @brief addInterface Adds and bind a interface to a resource
 *
 * @param resource      The resource to bind a type to
 * @param interface     Type to be bound and added
 *
 * @return OC_STACK_OK if successfully bound
 */
OCStackResult addInterface(OCBaseResourceT *resource, OCResourceInterface *interface)
{
    OCResourceInterface *current = resource->interface;

    // Loop through the linked list of ind the tail element
    while(current->next != NULL)
    {
        current = current->next;
    }

    current->next = (OCResourceInterface*)malloc(sizeof(OCResourceInterface));
    if(current->next == NULL) {printNoMemoryMsg(); return OC_STACK_NO_MEMORY;}
    memcpy(current->next, interface, sizeof(OCResourceInterface));

    OCStackResult result = OCBindResourceInterfaceToResource(resource->handle, interface->name);

    //OIC_LOG_V(INFO, TAG, "Result of type binding: %s", getOCStackResult(result));
    OIC_LOG_V(INFO, TAG, "Interface added: %s", interface->name);


    free(interface);

    return result;
}
Esempio n. 8
0
OCStackResult InitializeKeepAlive(OCMode mode)
{
    OIC_LOG(DEBUG, TAG, "InitializeKeepAlive IN");
    if (g_isKeepAliveInitialized)
    {
        OIC_LOG(DEBUG, TAG, "KeepAlive already initialized");
        return OC_STACK_OK;
    }

    if (OC_CLIENT != mode)
    {
        // Create the KeepAlive Resource[/oic/ping].
        OCStackResult result = CreateKeepAliveResource();
        if (OC_STACK_OK != result)
        {
            OIC_LOG_V(ERROR, TAG, "CreateKeepAliveResource failed[%d]", result);
            return result;
        }
    }

    if (!g_keepAliveConnectionTable)
    {
        g_keepAliveConnectionTable = u_arraylist_create();
        if (NULL == g_keepAliveConnectionTable)
        {
            OIC_LOG(ERROR, TAG, "Creating KeepAlive Table failed");
            TerminateKeepAlive(mode);
            return OC_STACK_ERROR;
        }
    }

    g_isKeepAliveInitialized = true;

    OIC_LOG(DEBUG, TAG, "InitializeKeepAlive OUT");
    return OC_STACK_OK;
}
Esempio n. 9
0
jint CALEGetBuildVersion(JNIEnv *env)
{
    VERIFY_NON_NULL_RET(env, TAG, "env is null", -1);

    // VERSION is a nested class within android.os.Build (hence "$" rather than "/")
    jclass jni_cls_version = (*env)->FindClass(env, "android/os/Build$VERSION");
    if (!jni_cls_version)
    {
        OIC_LOG(ERROR, TAG, "jni_cls_version is null");
        return -1;
    }

    jfieldID jni_fid_sdk = (*env)->GetStaticFieldID(env, jni_cls_version, "SDK_INT", "I");
    if (!jni_fid_sdk)
    {
        OIC_LOG(ERROR, TAG, "jni_fid_sdk is null");
        return -1;
    }

    jint jni_int_sdk = (*env)->GetStaticIntField(env, jni_cls_version, jni_fid_sdk);
    OIC_LOG_V(DEBUG, TAG, "sdk version is %d", jni_int_sdk);

    return jni_int_sdk;
}
Esempio n. 10
0
void OCPayloadDestroy(OCPayload* payload)
{
    if (!payload)
    {
        return;
    }

    switch(payload->type)
    {
        case PAYLOAD_TYPE_REPRESENTATION:
            OCRepPayloadDestroy((OCRepPayload*)payload);
            break;
        case PAYLOAD_TYPE_DISCOVERY:
            OCDiscoveryPayloadDestroy((OCDiscoveryPayload*)payload);
            break;
        case PAYLOAD_TYPE_DEVICE:
            OCDevicePayloadDestroy((OCDevicePayload*)payload);
            break;
        case PAYLOAD_TYPE_PLATFORM:
            OCPlatformPayloadDestroy((OCPlatformPayload*)payload);
            break;
        case PAYLOAD_TYPE_PRESENCE:
            OCPresencePayloadDestroy((OCPresencePayload*)payload);
            break;
        case PAYLOAD_TYPE_SECURITY:
            OCSecurityPayloadDestroy((OCSecurityPayload*)payload);
            break;
        case PAYLOAD_TYPE_RD:
           OCRDPayloadDestroy((OCRDPayload*)payload);
           break;
        default:
            OIC_LOG_V(ERROR, TAG, "Unsupported payload type in destroy: %d", payload->type);
            OICFree(payload);
            break;
    }
}
Esempio n. 11
0
int DeviceDiscovery()
{
    OCStackResult ret;
    OCCallbackData cbData;
    char queryUri[200];
    char ipaddr[100] = { '\0' };

    snprintf(queryUri, sizeof (queryUri), DISCOVERY_QUERY, ipaddr);

    cbData.cb = discoveryReqCB;
    cbData.context = NULL;
    cbData.cd = NULL;

    /* Start a discovery query*/
    OIC_LOG_V(INFO, TAG, "Resource Discovery : %s\n", queryUri);

    ret = OCDoResource(NULL, OC_REST_DISCOVER, queryUri, 0, 0, CT_DEFAULT,
                       OC_LOW_QOS, &cbData, NULL, 0);
    if (ret != OC_STACK_OK)
    {
        OIC_LOG(ERROR, TAG, "OCStack resource error");
    }
    return ret;
}
Esempio n. 12
0
CAResult_t CAArduinoInitUdpSocket(uint16_t *port, int *socketID)
{
    OIC_LOG(DEBUG, TAG, "IN");
    VERIFY_NON_NULL(port, TAG, "port");
    VERIFY_NON_NULL(socketID, TAG, "socketID");

    CAResult_t ret = CAArduinoGetAvailableSocket(socketID);
    if (ret != CA_STATUS_OK)
    {
        OIC_LOG(ERROR, TAG, "get sock fail");
        return ret;
    }

    //Create a datagram socket on which to recv/send.
    if (!socket(*socketID, SnMR::UDP, *port, 0))
    {
        OIC_LOG(ERROR, TAG, "sock fail");
        return CA_STATUS_FAILED;
    }

    OIC_LOG_V(DEBUG, TAG, "socketId:%d", *socketID);
    OIC_LOG(DEBUG, TAG, "OUT");
    return CA_STATUS_OK;
}
Esempio n. 13
0
int main() {
    OIC_LOG_V(INFO, TAG, "Starting ocserver");
    if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK) {
        OIC_LOG(ERROR, TAG, "OCStack init error");
        return 0;
    }

    /*
     * Declare and create the example resource: Light
     */
    if(createLightResource() != OC_STACK_OK)
    {
        OIC_LOG(ERROR, TAG, "OCStack cannot create resource...");
    }

    // Break from loop with Ctrl-C
    OIC_LOG(INFO, TAG, "Entering ocserver main loop...");
    signal(SIGINT, handleSigInt);
    while (!gQuitFlag) {

        if (OCProcess() != OC_STACK_OK) {
            OIC_LOG(ERROR, TAG, "OCStack process error");
            return 0;
        }

        sleep(1);
    }

    OIC_LOG(INFO, TAG, "Exiting ocserver main loop...");

    if (OCStop() != OC_STACK_OK) {
        OIC_LOG(ERROR, TAG, "OCStack process error");
    }

    return 0;
}
Esempio n. 14
0
static void sendMulticastData4(const u_arraylist_t *iflist,
                               CAEndpoint_t *endpoint,
                               const void *data, uint32_t datalen)
{
    struct ip_mreq mreq = { .imr_multiaddr = IPv4MulticastAddress };
    OICStrcpy(endpoint->addr, sizeof(endpoint->addr), IPv4_MULTICAST);
    int fd = caglobals.ip.u4.fd;

    uint32_t len = u_arraylist_length(iflist);
    for (uint32_t i = 0; i < len; i++)
    {
        CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
        if (!ifitem)
        {
            continue;
        }
        if ((ifitem->flags & (IFF_UP|IFF_RUNNING)) != (IFF_UP|IFF_RUNNING))
        {
            continue;
        }
        if (ifitem->family != AF_INET)
        {
            continue;
        }

        struct in_addr inaddr;
        inaddr.s_addr = ifitem->ipv4addr;
        mreq.imr_interface = inaddr;
        if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF, &mreq, sizeof (mreq)))
        {
            OIC_LOG_V(ERROR, TAG, "send IP_MULTICAST_IF failed: %s (using defualt)",
                    strerror(errno));
        }
        sendData(fd, endpoint, data, datalen, "multicast", "ipv4");
    }
}
Esempio n. 15
0
void CAAdapterRecvData(const char *remoteAddress, const uint8_t *data, uint32_t dataLength,
                       uint32_t *sentLength)
{
    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");

    if (false == g_adapterState)
    {
        OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Bluetooth adapter is disabled!");
        *sentLength = 0;
        return;
    }

    // Input validation
    VERIFY_NON_NULL_VOID(data, EDR_ADAPTER_TAG, "Data is null");
    VERIFY_NON_NULL_VOID(sentLength, EDR_ADAPTER_TAG, "Sent data length holder is null");

    // Create remote endpoint
    CAEndpoint_t *remoteEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS,
                                                          CA_ADAPTER_RFCOMM_BTEDR,
                                                          remoteAddress, 0);
    if (NULL == remoteEndpoint)
    {
        OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to create remote endpoint !");
        return;
    }

    // Add message to data queue
    CAEDRData *edrData =  CACreateEDRData(remoteEndpoint, data, dataLength);
    CAQueueingThreadAddData(g_recvQueueHandle, edrData, sizeof(CAEDRData));
    *sentLength = dataLength;

    // Free remote endpoint
    CAFreeEndpoint(remoteEndpoint);

    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
}
Esempio n. 16
0
CAResult_t CAStartServer()
{
    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");

    CAResult_t err = CA_STATUS_OK;

    if (false == g_adapterState)
    {
        OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "Bluetooth adapter is disabled!");
        // Setting g_serverState for starting Rfcommserver when adapter starts
        g_serverState = true;
        return CA_STATUS_OK;
    }

    if (CA_STATUS_OK != (err = CAEDRServerStart(g_edrThreadPool)))
    {
        OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Failed to start RFCOMM server!, error num [%d]",
                  err);
        return err;
    }

    OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
    return err;
}
Esempio n. 17
0
int InitDeviceDiscovery(OCQualityOfService qos)
{
    OIC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);

    OCStackResult ret;
    OCCallbackData cbData;
    char szQueryUri[100] = { 0 };

    snprintf(szQueryUri, sizeof (szQueryUri) - 1, DEVICE_DISCOVERY_QUERY, discoveryAddr);

    cbData.cb = DeviceDiscoveryReqCB;
    cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
    cbData.cd = NULL;

    ret = OCDoResource(NULL, OC_REST_DISCOVER, szQueryUri, NULL, 0, CT_DEFAULT,
                       (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS,
                       &cbData, NULL, 0);
    if (ret != OC_STACK_OK)
    {
        OIC_LOG(ERROR, TAG, "OCStack device error");
    }

    return ret;
}
Esempio n. 18
0
BrokerID ResourceBroker::hostResource(PrimitiveResourcePtr pResource, BrokerCB cb)
{
    OIC_LOG_V(DEBUG, BROKER_TAG, "hostResource().");
    if(pResource == nullptr || cb == nullptr || cb == NULL)
    {
        throw InvalidParameterException("[hostResource] input parameter(PrimitiveResource or BrokerCB) is Invalid");
    }

    BrokerID retID = generateBrokerID();

    ResourcePresencePtr presenceItem = findResourcePresence(pResource);
    if(presenceItem == nullptr)
    {
        OIC_LOG_V(DEBUG, BROKER_TAG, "Not found any Handled Resource.");
        OIC_LOG_V(DEBUG, BROKER_TAG, "Create New Resource Presence Handler.");

        try
        {
            OIC_LOG_V(DEBUG, BROKER_TAG, "create the ResourcePresence.");
            presenceItem.reset(new ResourcePresence());
            presenceItem->initializeResourcePresence(pResource);
        } catch(RCSPlatformException &e)
        {
            throw FailedSubscribePresenceException(e.getReasonCode());
        }
        if(s_presenceList != nullptr)
        {
            OIC_LOG_V(DEBUG, BROKER_TAG, "push the ResourcePresence in presenceList.");
            s_presenceList->push_back(presenceItem);
        }
    }
    OIC_LOG_V(DEBUG, BROKER_TAG, "add the BrokerRequester in ResourcePresence.");
    presenceItem->addBrokerRequester(retID, cb);

    BrokerCBResourcePair pair(presenceItem, cb);
    s_brokerIDMap->insert(std::pair<BrokerID, BrokerCBResourcePair>
                          (retID, BrokerCBResourcePair(presenceItem, cb)));

    return retID;
}
Esempio n. 19
0
static void printCred(const OicSecCred_t * cred)
{
    EXPECT_TRUE(NULL != cred);

    const OicSecCred_t *credTmp1 = NULL;
    for (credTmp1 = cred; credTmp1; credTmp1 = credTmp1->next)
    {
        OIC_LOG_V(INFO, TAG, "\ncred->credId = %d", credTmp1->credId);
        OIC_LOG_V(INFO, TAG, "cred->subject.id = %s", credTmp1->subject.id);
        OIC_LOG_V(INFO, TAG, "cred->credType = %d", credTmp1->credType);
        if(credTmp1->privateData.data)
        {
            OIC_LOG_V(INFO, TAG, "cred->privateData.data = %s", credTmp1->privateData.data);
        }
#ifdef __WITH_X509__
        if(credTmp1->publicData.data)
        {
           OIC_LOG_V(INFO, TAG, "cred->publicData.data = %s", credTmp1->publicData.data);
        }
#endif /* __WITH_X509__ */
	OIC_LOG_V(INFO, TAG, "cred->rownerID = %s", credTmp1->rownerID.id);
    }
}
Esempio n. 20
0
static void ConvertJsonToCBOR(const char *jsonFileName, const char *cborFileName)
{
    char *jsonStr = NULL;
    FILE *fp = NULL;
    FILE *fp1 = NULL;
    uint8_t *aclCbor = NULL;
    uint8_t *pstatCbor = NULL;
    uint8_t *doxmCbor = NULL;
    uint8_t *amaclCbor = NULL;
    uint8_t *svcCbor = NULL;
    uint8_t *credCbor = NULL;
    cJSON *jsonRoot = NULL;
    OCStackResult ret = OC_STACK_ERROR;
    size_t size = GetJSONFileSize(jsonFileName);
    if (0 == size)
    {
        OIC_LOG (ERROR, TAG, "Failed converting to JSON");
        return;
    }

    jsonStr = (char *)OICMalloc(size + 1);
    VERIFY_NON_NULL(TAG, jsonStr, FATAL);

    fp = fopen(jsonFileName, "r");
    if (fp)
    {
        size_t bytesRead = fread(jsonStr, 1, size, fp);
        jsonStr[bytesRead] = '\0';

        OIC_LOG_V(DEBUG, TAG, "Read %zu bytes", bytesRead);
        fclose(fp);
        fp = NULL;
    }
    else
    {
        OIC_LOG (ERROR, TAG, "Unable to open JSON file!!");
        goto exit;
    }

    jsonRoot = cJSON_Parse(jsonStr);

    cJSON *value = cJSON_GetObjectItem(jsonRoot, OIC_JSON_ACL_NAME);
    //printf("ACL json : \n%s\n", cJSON_PrintUnformatted(value));
    size_t aclCborSize = 0;
    if (NULL != value)
    {
        OicSecAcl_t *acl = JSONToAclBin(jsonStr);
        VERIFY_NON_NULL(TAG, acl, FATAL);
        ret = AclToCBORPayload(acl, &aclCbor, &aclCborSize);
        if(OC_STACK_OK != ret)
        {
            OIC_LOG (ERROR, TAG, "Failed converting Acl to Cbor Payload");
            DeleteACLList(acl);
            goto exit;
        }
        printf("ACL Cbor Size: %zd\n", aclCborSize);
        DeleteACLList(acl);
    }

    value = cJSON_GetObjectItem(jsonRoot, OIC_JSON_PSTAT_NAME);
    size_t pstatCborSize = 0;
    if (NULL != value)
    {
        OicSecPstat_t *pstat = JSONToPstatBin(jsonStr);
        VERIFY_NON_NULL(TAG, pstat, FATAL);
        ret = PstatToCBORPayload(pstat, &pstatCbor, &pstatCborSize);
        if(OC_STACK_OK != ret)
        {
            OIC_LOG (ERROR, TAG, "Failed converting Pstat to Cbor Payload");
            DeletePstatBinData(pstat);
            goto exit;
        }
        printf("PSTAT Cbor Size: %zd\n", pstatCborSize);
        DeletePstatBinData(pstat);
    }
    value = cJSON_GetObjectItem(jsonRoot, OIC_JSON_DOXM_NAME);
    size_t doxmCborSize = 0;
    if (NULL != value)
    {
        OicSecDoxm_t *doxm = JSONToDoxmBin(jsonStr);
        VERIFY_NON_NULL(TAG, doxm, FATAL);
        ret = DoxmToCBORPayload(doxm, &doxmCbor, &doxmCborSize);
        if(OC_STACK_OK != ret)
        {
            OIC_LOG (ERROR, TAG, "Failed converting Doxm to Cbor Payload");
            DeleteDoxmBinData(doxm);
            goto exit;
        }
        printf("DOXM Cbor Size: %zd\n", doxmCborSize);
        DeleteDoxmBinData(doxm);
    }
    value = cJSON_GetObjectItem(jsonRoot, OIC_JSON_AMACL_NAME);
    size_t amaclCborSize = 0;
    if (NULL != value)
    {
        OicSecAmacl_t *amacl = JSONToAmaclBin(jsonStr);
        VERIFY_NON_NULL(TAG, amacl, FATAL);
        ret = AmaclToCBORPayload(amacl, &amaclCbor, &amaclCborSize);
        if(OC_STACK_OK != ret)
        {
            OIC_LOG (ERROR, TAG, "Failed converting Amacl to Cbor Payload");
            DeleteAmaclList(amacl);
            goto exit;
        }
        printf("AMACL Cbor Size: %zd\n", amaclCborSize);
        DeleteAmaclList(amacl);
    }
    value = cJSON_GetObjectItem(jsonRoot, OIC_JSON_SVC_NAME);
    size_t svcCborSize = 0;
    if (NULL != value)
    {
        OicSecSvc_t *svc = JSONToSvcBin(jsonStr);
        VERIFY_NON_NULL(TAG, svc, FATAL);
        ret = SVCToCBORPayload(svc, &svcCbor, &svcCborSize);
        if(OC_STACK_OK != ret)
        {
            OIC_LOG (ERROR, TAG, "Failed converting Svc to Cbor Payload");
            DeleteSVCList(svc);
            goto exit;
        }
        printf("SVC Cbor Size: %zd\n", svcCborSize);
        DeleteSVCList(svc);
    }
    value = cJSON_GetObjectItem(jsonRoot, OIC_JSON_CRED_NAME);
    //printf("CRED json : \n%s\n", cJSON_PrintUnformatted(value));
    size_t credCborSize = 0;
    int secureFlag = 0;
    if (NULL != value)
    {
        OicSecCred_t *cred = JSONToCredBin(jsonStr);
        VERIFY_NON_NULL(TAG, cred, FATAL);
        ret = CredToCBORPayload(cred, &credCbor, &credCborSize, secureFlag);
        if(OC_STACK_OK != ret)
        {
            OIC_LOG (ERROR, TAG, "Failed converting Cred to Cbor Payload");
            DeleteCredList(cred);
            goto exit;
        }
        printf("CRED Cbor Size: %zd\n", credCborSize);
        DeleteCredList(cred);
    }

    CborEncoder encoder;
    size_t cborSize = aclCborSize + pstatCborSize + doxmCborSize + svcCborSize + credCborSize + amaclCborSize;

    printf("Total Cbor Size : %zd\n", cborSize);
    cborSize += 255; // buffer margin for adding map and byte string
    uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborSize);
    VERIFY_NON_NULL(TAG, outPayload, ERROR);
    cbor_encoder_init(&encoder, outPayload, cborSize, 0);
    CborEncoder map;
    CborError cborEncoderResult = cbor_encoder_create_map(&encoder, &map, CborIndefiniteLength);
    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Creating Main Map.");
    if (aclCborSize > 0)
    {
        cborEncoderResult = cbor_encode_text_string(&map, OIC_JSON_ACL_NAME, strlen(OIC_JSON_ACL_NAME));
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ACL Name.");
        cborEncoderResult = cbor_encode_byte_string(&map, aclCbor, aclCborSize);
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ACL Value.");
    }

    if (pstatCborSize > 0)
    {
        cborEncoderResult = cbor_encode_text_string(&map, OIC_JSON_PSTAT_NAME, strlen(OIC_JSON_PSTAT_NAME));
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding PSTAT Name.");
        cborEncoderResult = cbor_encode_byte_string(&map, pstatCbor, pstatCborSize);
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding PSTAT Value.");
    }
    if (doxmCborSize > 0)
    {
        cborEncoderResult = cbor_encode_text_string(&map, OIC_JSON_DOXM_NAME, strlen(OIC_JSON_DOXM_NAME));
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding DOXM Name.");
        cborEncoderResult = cbor_encode_byte_string(&map, doxmCbor, doxmCborSize);
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding DOXM Value.");
    }
    if (amaclCborSize > 0)
    {
        cborEncoderResult = cbor_encode_text_string(&map, OIC_JSON_AMACL_NAME, strlen(OIC_JSON_AMACL_NAME));
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding AMACL Name.");
        cborEncoderResult = cbor_encode_byte_string(&map, amaclCbor, amaclCborSize);
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding AMACL Value.");
    }
    if (svcCborSize > 0)
    {
        cborEncoderResult = cbor_encode_text_string(&map, OIC_JSON_SVC_NAME, strlen(OIC_JSON_SVC_NAME));
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SVC Name.");
        cborEncoderResult = cbor_encode_byte_string(&map, svcCbor, svcCborSize);
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SVC Value.");
    }
    if (credCborSize > 0)
    {
        cborEncoderResult = cbor_encode_text_string(&map, OIC_JSON_CRED_NAME, strlen(OIC_JSON_CRED_NAME));
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding CRED Name.");
        cborEncoderResult = cbor_encode_byte_string(&map, credCbor, credCborSize);
        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding CRED Value.");
    }

    cborEncoderResult = cbor_encoder_close_container(&encoder, &map);
    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Container.");

    size_t s = encoder.ptr - outPayload;
    OIC_LOG_V(DEBUG, TAG, "Payload size %zu", s);

    fp1 = fopen(cborFileName, "w");
    if (fp1)
    {
        size_t bytesWritten = fwrite(outPayload, 1, s, fp1);
        if (bytesWritten == s)
        {
            OIC_LOG_V(DEBUG, TAG, "Written %zu bytes", bytesWritten);
        }
        else
        {
            OIC_LOG_V(ERROR, TAG, "Failed writing %zu bytes", s);
        }
        fclose(fp1);
        fp1 = NULL;
    }
exit:

    cJSON_Delete(jsonRoot);
    OICFree(aclCbor);
    OICFree(doxmCbor);
    OICFree(pstatCbor);
    OICFree(amaclCbor);
    OICFree(svcCbor);
    OICFree(credCbor);
    OICFree(jsonStr);
    return ;
}
Esempio n. 21
0
CAResult_t CAGetNetworkInfo(CAEndpoint_t **info, uint32_t *size)
{
    if (info == NULL || size == NULL)
    {
        return CA_STATUS_INVALID_PARAM;
    }

    CAEndpoint_t *tempInfo[CA_TRANSPORT_TYPE_NUM] = { 0 };
    uint32_t tempSize[CA_TRANSPORT_TYPE_NUM] = { 0 };

    CAResult_t res = CA_STATUS_FAILED;
    uint32_t resSize = 0;
    for (int index = 0; index < CA_TRANSPORT_TYPE_NUM; index++)
    {
        if (g_adapterHandler[index].GetnetInfo != NULL)
        {
            // #1. get information for each adapter
            res = g_adapterHandler[index].GetnetInfo(&tempInfo[index],
                                                     &tempSize[index]);

            // #2. total size
            if (res == CA_STATUS_OK)
            {
                resSize += tempSize[index];
            }

            OIC_LOG_V(DEBUG,
                      TAG,
                      "%d adapter network info size is %" PRIu32 " res:%d",
                      index,
                      tempSize[index],
                      res);
        }
    }

    OIC_LOG_V(DEBUG, TAG, "network info total size is %d!", resSize);

    if (resSize == 0)
    {
        if (res == CA_ADAPTER_NOT_ENABLED || res == CA_NOT_SUPPORTED)
        {
            return res;
        }
        return CA_STATUS_FAILED;
    }

    // #3. add data into result
    // memory allocation
    CAEndpoint_t *resInfo = (CAEndpoint_t *) OICCalloc(resSize, sizeof (*resInfo));
    CA_MEMORY_ALLOC_CHECK(resInfo);

    // #4. save data
    *info = resInfo;
    *size = resSize;

    for (int index = 0; index < CA_TRANSPORT_TYPE_NUM; index++)
    {
        // check information
        if (tempSize[index] == 0)
        {
            continue;
        }

        memcpy(resInfo,
               tempInfo[index],
               sizeof(*resInfo) * tempSize[index]);

        resInfo += tempSize[index];

        // free adapter data
        OICFree(tempInfo[index]);
        tempInfo[index] = NULL;
    }

    OIC_LOG(DEBUG, TAG, "each network info save success!");
    return CA_STATUS_OK;

    // memory error label.
memory_error_exit:

    for (int index = 0; index < CA_TRANSPORT_TYPE_NUM; index++)
    {

        OICFree(tempInfo[index]);
        tempInfo[index] = NULL;
    }

    return CA_MEMORY_ALLOC_FAILED;
}
Esempio n. 22
0
CAInterface_t *CAFindInterfaceChange()
{
    char buf[MAX_INTERFACE_INFO_LENGTH] = { 0 };
    struct ifconf ifc  = { .ifc_len = MAX_INTERFACE_INFO_LENGTH, .ifc_buf = buf };

    int s = caglobals.ip.u6.fd != -1 ? caglobals.ip.u6.fd : caglobals.ip.u4.fd;
    if (ioctl(s, SIOCGIFCONF, &ifc) < 0)
    {
        OIC_LOG_V(ERROR, TAG, "SIOCGIFCONF failed: %s", strerror(errno));
        return NULL;
    }

    CAInterface_t *foundNewInterface = NULL;

    struct ifreq* ifr = ifc.ifc_req;
    size_t interfaces = ifc.ifc_len / sizeof (ifc.ifc_req[0]);
    size_t ifreqsize = ifc.ifc_len;

    CAIfItem_t *previous = (CAIfItem_t *)OICMalloc(ifreqsize);
    if (!previous)
    {
        OIC_LOG(ERROR, TAG, "OICMalloc failed");
        return NULL;
    }

    memcpy(previous, caglobals.ip.nm.ifItems, ifreqsize);
    size_t numprevious = caglobals.ip.nm.numIfItems;

    if (ifreqsize > caglobals.ip.nm.sizeIfItems)
    {

        CAIfItem_t *items = (CAIfItem_t *)OICRealloc(caglobals.ip.nm.ifItems, ifreqsize);
        if (!items)
        {
            OIC_LOG(ERROR, TAG, "OICRealloc failed");
            OICFree(previous);
            return NULL;
        }
        caglobals.ip.nm.ifItems = items;
        caglobals.ip.nm.sizeIfItems = ifreqsize;
    }

    caglobals.ip.nm.numIfItems = 0;
    for (size_t i = 0; i < interfaces; i++)
    {
        struct ifreq* item = &ifr[i];
        char *name = item->ifr_name;
        struct sockaddr_in *sa4 = (struct sockaddr_in *)&item->ifr_addr;
        uint32_t ipv4addr = sa4->sin_addr.s_addr;

        if (ioctl(s, SIOCGIFFLAGS, item) < 0)
        {
            OIC_LOG_V(ERROR, TAG, "SIOCGIFFLAGS failed: %s", strerror(errno));
            continue;
        }
        int16_t flags = item->ifr_flags;
        if ((flags & IFF_LOOPBACK) || !(flags & IFF_RUNNING))
        {
            continue;
        }
        if (ioctl(s, SIOCGIFINDEX, item) < 0)
        {
            OIC_LOG_V(ERROR, TAG, "SIOCGIFINDEX failed: %s", strerror(errno));
            continue;
        }

        int ifIndex = item->ifr_ifindex;
        caglobals.ip.nm.ifItems[i].ifIndex = ifIndex;  // refill interface list
        caglobals.ip.nm.numIfItems++;

        if (foundNewInterface)
        {
            continue;   // continue updating interface list
        }

        // see if this interface didn't previously exist
        bool found = false;
        for (size_t j = 0; j < numprevious; j++)
        {
            if (ifIndex == previous[j].ifIndex)
            {
                found = true;
                break;
            }
        }
        if (found)
        {
            OIC_LOG_V(INFO, TAG, "Interface found: %s", name);
            continue;
        }

        foundNewInterface = CANewInterfaceItem(ifIndex, name, AF_INET, ipv4addr, flags);
    }

    OICFree(previous);
    return foundNewInterface;
}
Esempio n. 23
0
u_arraylist_t *CAIPGetInterfaceInformation(int desiredIndex)
{
    u_arraylist_t *iflist = u_arraylist_create();
    if (!iflist)
    {
        OIC_LOG_V(ERROR, TAG, "Failed to create iflist: %s", strerror(errno));
        return NULL;
    }

    char buf[MAX_INTERFACE_INFO_LENGTH] = { 0 };
    struct ifconf ifc = { .ifc_len = MAX_INTERFACE_INFO_LENGTH, .ifc_buf = buf };

    int s = caglobals.ip.u6.fd != -1 ? caglobals.ip.u6.fd : caglobals.ip.u4.fd;
    if (ioctl(s, SIOCGIFCONF, &ifc) < 0)
    {
        OIC_LOG_V(ERROR, TAG, "SIOCGIFCONF failed: %s", strerror(errno));
        u_arraylist_destroy(iflist);
        return NULL;
    }

    struct ifreq* ifr = ifc.ifc_req;
    size_t interfaces = ifc.ifc_len / sizeof (ifc.ifc_req[0]);
    size_t ifreqsize = ifc.ifc_len;

    if (ifreqsize > caglobals.ip.nm.sizeIfItems)
    {
        CAIfItem_t *items = (CAIfItem_t *)OICRealloc(caglobals.ip.nm.ifItems, ifreqsize);
        if (!items)
        {
            OIC_LOG(ERROR, TAG, "OICRealloc failed");
            goto exit;
        }
        caglobals.ip.nm.ifItems = items;
        caglobals.ip.nm.sizeIfItems = ifreqsize;
    }

    caglobals.ip.nm.numIfItems = 0;
    for (size_t i = 0; i < interfaces; i++)
    {
        CAResult_t result = CA_STATUS_OK;
        struct ifreq* item = &ifr[i];
        char *name = item->ifr_name;
        struct sockaddr_in *sa4 = (struct sockaddr_in *)&item->ifr_addr;
        uint32_t ipv4addr = sa4->sin_addr.s_addr;

        if (ioctl(s, SIOCGIFFLAGS, item) < 0)
        {
            OIC_LOG_V(ERROR, TAG, "SIOCGIFFLAGS failed: %s", strerror(errno));
            continue;
        }
        int16_t flags = item->ifr_flags;
        if ((flags & IFF_LOOPBACK) || !(flags & IFF_RUNNING))
        {
            continue;
        }
        if (ioctl(s, SIOCGIFINDEX, item) < 0)
        {
            OIC_LOG_V(ERROR, TAG, "SIOCGIFINDEX failed: %s", strerror(errno));
            continue;
        }

        int ifindex = item->ifr_ifindex;
        caglobals.ip.nm.ifItems[i].ifIndex = ifindex;
        caglobals.ip.nm.numIfItems++;

        if (desiredIndex && (ifindex != desiredIndex))
        {
            continue;
        }

        // Add IPv4 interface
        result = CAAddInterfaceItem(iflist, ifindex, name, AF_INET, ipv4addr, flags);
        if (CA_STATUS_OK != result)
        {
            goto exit;
        }

        // Add IPv6 interface
        result = CAAddInterfaceItem(iflist, ifindex, name, AF_INET6, ipv4addr, flags);
        if (CA_STATUS_OK != result)
        {
            goto exit;
        }
    }
    return iflist;

exit:
    u_arraylist_destroy(iflist);
    return NULL;
}
void CACheckData()
{
    CABleDoEvents();

    if (CAIsBleDataAvailable())
    {
        // Allocate Memory for COAP Buffer and do ParseHeader
        if (NULL == g_coapBuffer)
        {
            OIC_LOG(DEBUG, TAG, "IN");
            char headerArray[CA_HEADER_LENGTH] = "";
            while (CAIsBleDataAvailable() && g_dataLen < CA_HEADER_LENGTH)
            {
                headerArray[g_dataLen++] = CAReadBleData();
            }

            g_packetDataLen = CAParseHeader(headerArray);

            if (g_packetDataLen > COAP_MAX_PDU_SIZE)
            {
                OIC_LOG(ERROR, TAG, "len > pdu_size");
                return;
            }

            g_coapBuffer = (char *)OICCalloc(g_packetDataLen, sizeof(char));
            if (NULL == g_coapBuffer)
            {
                OIC_LOG(ERROR, TAG, "malloc");
                return;
            }

            OIC_LOG(DEBUG, TAG, "OUT");
            g_dataLen = 0;
        }

        OIC_LOG(DEBUG, TAG, "IN");
        while (CAIsBleDataAvailable())
        {
            OIC_LOG(DEBUG, TAG, "In While loop");
            g_coapBuffer[g_dataLen++] = CAReadBleData();
            if (g_dataLen == g_packetDataLen)
            {
                OIC_LOG(DEBUG, TAG, "Read Comp BLE Pckt");
                g_coapBuffer[g_dataLen] = '\0';
                if (g_dataLen > 0)
                {
                    OIC_LOG_V(DEBUG, TAG, "recv dataLen=%d", g_dataLen);
                    CANotifyCallback((void *)g_coapBuffer, g_dataLen, "", 0);
                }
                g_dataLen = 0;
                OICFree(g_coapBuffer);
                g_coapBuffer = NULL;
                break;
            }
        }
        OIC_LOG(DEBUG, TAG, "OUT");
    }
    else
    {
        OIC_LOG(DEBUG, TAG, "NoData");
    }
    return;
}
Esempio n. 25
0
CAResult_t CAIPStartServer(const ca_thread_pool_t threadPool)
{
    CAResult_t res = CA_STATUS_OK;

    if (caglobals.ip.started)
    {
        return res;
    }

    if (!IPv4MulticastAddress.s_addr)
    {
        (void)inet_aton(IPv4_MULTICAST, &IPv4MulticastAddress);
        (void)inet_pton(AF_INET6, IPv6_MULTICAST_INT, &IPv6MulticastAddressInt);
        (void)inet_pton(AF_INET6, IPv6_MULTICAST_LNK, &IPv6MulticastAddressLnk);
        (void)inet_pton(AF_INET6, IPv6_MULTICAST_RLM, &IPv6MulticastAddressRlm);
        (void)inet_pton(AF_INET6, IPv6_MULTICAST_ADM, &IPv6MulticastAddressAdm);
        (void)inet_pton(AF_INET6, IPv6_MULTICAST_SIT, &IPv6MulticastAddressSit);
        (void)inet_pton(AF_INET6, IPv6_MULTICAST_ORG, &IPv6MulticastAddressOrg);
        (void)inet_pton(AF_INET6, IPv6_MULTICAST_GLB, &IPv6MulticastAddressGlb);
    }

    if (!caglobals.ip.ipv6enabled && !caglobals.ip.ipv4enabled)
    {
        caglobals.ip.ipv4enabled = true;  // only needed to run CA tests
    }

    if (caglobals.ip.ipv6enabled)
    {
        NEWSOCKET(AF_INET6, u6)
        NEWSOCKET(AF_INET6, u6s)
        NEWSOCKET(AF_INET6, m6)
        NEWSOCKET(AF_INET6, m6s)
        OIC_LOG_V(INFO, TAG, "IPv6 unicast port: %u", caglobals.ip.u6.port);
    }
    if (caglobals.ip.ipv4enabled)
    {
        NEWSOCKET(AF_INET, u4)
        NEWSOCKET(AF_INET, u4s)
        NEWSOCKET(AF_INET, m4)
        NEWSOCKET(AF_INET, m4s)
        OIC_LOG_V(INFO, TAG, "IPv4 unicast port: %u", caglobals.ip.u4.port);
    }

    OIC_LOG_V(DEBUG, TAG,
              "socket summary: u6=%d, u6s=%d, u4=%d, u4s=%d, m6=%d, m6s=%d, m4=%d, m4s=%d",
                             caglobals.ip.u6.fd, caglobals.ip.u6s.fd,
                             caglobals.ip.u4.fd, caglobals.ip.u4s.fd,
                             caglobals.ip.m6.fd, caglobals.ip.m6s.fd,
                             caglobals.ip.m4.fd, caglobals.ip.m4s.fd);

    // create pipe for fast shutdown
    CAInitializePipe();
    CHECKFD(caglobals.ip.shutdownFds[0]);
    CHECKFD(caglobals.ip.shutdownFds[1]);

    // create source of network interface change notifications
    CAInitializeNetlink();

    caglobals.ip.selectTimeout = CAGetPollingInterval(caglobals.ip.selectTimeout);

    CAApplyInterfaces();

    caglobals.ip.terminate = false;
    res = ca_thread_pool_add_task(threadPool, CAReceiveHandler, NULL);
    if (CA_STATUS_OK != res)
    {
        OIC_LOG(ERROR, TAG, "thread_pool_add_task failed");
        return res;
    }
    OIC_LOG(DEBUG, TAG, "CAReceiveHandler thread started successfully.");

    caglobals.ip.started = true;
    return CA_STATUS_OK;
}
Esempio n. 26
0
static int CACreateSocket(int family, uint16_t *port)
{
    int socktype = SOCK_DGRAM;
    #ifdef SOCK_CLOEXEC
    socktype |= SOCK_CLOEXEC;
    #endif
    int fd = socket(family, socktype, IPPROTO_UDP);
    if (-1 == fd)
    {
        OIC_LOG_V(ERROR, TAG, "create socket failed: %s", strerror(errno));
        return -1;
    }

    #ifndef SOCK_CLOEXEC
    int fl = fcntl(fd, F_GETFD);
    if (-1 == fl || -1 == fcntl(fd, F_SETFD, fl|FD_CLOEXEC))
    {
        OIC_LOG_V(ERROR, TAG, "set FD_CLOEXEC failed: %s", strerror(errno));
        close(fd);
        return -1;
    }
    #endif

    struct sockaddr_storage sa = { .ss_family = family };
    socklen_t socklen;

    if (family == AF_INET6)
    {
        int on = 1;
        if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)))
        {
            OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", strerror(errno));
        }
        ((struct sockaddr_in6 *)&sa)->sin6_port = htons(*port);
        socklen = sizeof (struct sockaddr_in6);
    }
    else
    {
        ((struct sockaddr_in *)&sa)->sin_port = htons(*port);
        socklen = sizeof (struct sockaddr_in);
    }

    if (*port)  // use the given port
    {
        int on = 1;
        if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof (on)))
        {
            OIC_LOG_V(ERROR, TAG, "SO_REUSEADDR failed: %s", strerror(errno));
            close(fd);
            return -1;
        }
    }

    if (-1 == bind(fd, (struct sockaddr *)&sa, socklen))
    {
        OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", strerror(errno));
        close(fd);
        return -1;
    }

    if (!*port)  // return the assigned port
    {
        if (-1 == getsockname(fd, (struct sockaddr *)&sa, &socklen))
        {
            OIC_LOG_V(ERROR, TAG, "getsockname failed: %s", strerror(errno));
            close(fd);
            return -1;
        }
        *port = ntohs(family == AF_INET6 ?
                      ((struct sockaddr_in6 *)&sa)->sin6_port :
                      ((struct sockaddr_in *)&sa)->sin_port);
    }

    return fd;
}
Esempio n. 27
0
// This is a function called back when a device is discovered
OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle /*handle*/,
                                        OCClientResponse * clientResponse)
{
    if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
    {
        OIC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
    }

    if (clientResponse)
    {
        OIC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));

        std::string connectionType = getConnectivityType (clientResponse->connType);
        OIC_LOG_V(INFO, TAG, "Discovered on %s", connectionType.c_str());
        OIC_LOG_V(INFO, TAG,
                "Device =============> Discovered @ %s:%d",
                clientResponse->devAddr.addr,
                clientResponse->devAddr.port);
        OIC_LOG_PAYLOAD(INFO, clientResponse->payload);

        ConnType = clientResponse->connType;
        serverAddr = clientResponse->devAddr;

        OCDiscoveryPayload *payload = (OCDiscoveryPayload*) clientResponse->payload;
        if (!payload)
        {
            return OC_STACK_DELETE_TRANSACTION;
        }

        OCResourcePayload *resource = (OCResourcePayload*) payload->resources;
        if (!resource)
        {
            OIC_LOG_V (INFO, TAG, "No resources in payload");
            return OC_STACK_DELETE_TRANSACTION;
        }
        coapServerResource =  resource->uri;

        switch(TestCase)
        {
            case TEST_GET_REQ_NON:
                InitGetRequest(OC_LOW_QOS, 0, 0);
                break;
            case TEST_GET_REQ_NON_WITH_FILTERS:
                InitGetRequest(OC_LOW_QOS, 0, 1);
                break;
            case TEST_PUT_REQ_NON:
                InitPutRequest(OC_LOW_QOS);
                break;
            case TEST_POST_REQ_NON:
                InitPostRequest(OC_LOW_QOS);
                break;
            case TEST_DELETE_REQ_NON:
                InitDeleteRequest(OC_LOW_QOS);
                break;
            case TEST_OBS_REQ_NON:
            case TEST_OBS_REQ_NON_CANCEL_IMM:
                InitObserveRequest(OC_LOW_QOS);
                break;
            case TEST_GET_UNAVAILABLE_RES_REQ_NON:
                InitGetRequestToUnavailableResource(OC_LOW_QOS);
                break;
            case TEST_GET_REQ_CON:
                InitGetRequest(OC_HIGH_QOS, 0, 0);
                break;
            case TEST_POST_REQ_CON:
                InitPostRequest(OC_HIGH_QOS);
                break;
            case TEST_DELETE_REQ_CON:
                InitDeleteRequest(OC_HIGH_QOS);
                break;
            case TEST_OBS_REQ_CON:
                InitObserveRequest(OC_HIGH_QOS);
                break;
#ifdef WITH_PRESENCE
            case TEST_OBS_PRESENCE:
            case TEST_OBS_PRESENCE_WITH_FILTER:
            case TEST_OBS_PRESENCE_WITH_FILTERS:
            case TEST_OBS_MULTICAST_PRESENCE:
                InitPresence();
                break;
#endif
            case TEST_GET_REQ_NON_WITH_VENDOR_HEADER_OPTIONS:
                InitGetRequest(OC_LOW_QOS, 1, 0);
                break;
            case TEST_DISCOVER_PLATFORM_REQ:
                InitPlatformDiscovery(OC_LOW_QOS);
                break;
            case TEST_DISCOVER_DEV_REQ:
                InitDeviceDiscovery(OC_LOW_QOS);
                break;
            default:
                PrintUsage();
                break;
        }
    }
    else
    {
        OIC_LOG_V(INFO, TAG, "discoveryReqCB received Null clientResponse");
    }
    return OC_STACK_KEEP_TRANSACTION;
}
OCStackApplicationResult ProvisionEnrolleeResponse(void *ctx, OCDoHandle handle,
                                                   OCClientResponse *clientResponse) {
    OIC_LOG_V(DEBUG, TAG, "INSIDE ProvisionEnrolleeResponse");

    // If user stopped the process then return from this function;
    if (IsSetupStopped()) {
        ErrorCallback(DEVICE_NOT_PROVISIONED);
        ClearMemory();
        return OC_STACK_DELETE_TRANSACTION;
    }

    ProvisioningInfo *provInfo;

    if (!ValidateEnrolleResponse(clientResponse)) {
        ErrorCallback(DEVICE_NOT_PROVISIONED);
        return OC_STACK_DELETE_TRANSACTION;
    }

    char *tnn;
    char *cd;

    OCRepPayload *input = (OCRepPayload * )(clientResponse->payload);

    while (input) {

        int64_t ps;
        if (OCRepPayloadGetPropInt(input, OC_RSRVD_ES_PS, &ps)) {

            if (ps == 1) {
                input = input->next;
                continue;
            }
            else {
                OIC_LOG_V(DEBUG, TAG, "PS is NOT proper");
                goto Error;

            }
        }

        if (OCRepPayloadGetPropString(input, OC_RSRVD_ES_TNN, &tnn)) {
            if (!strcmp(tnn, netProvInfo->netAddressInfo.WIFI.ssid)) {
                OIC_LOG_V(DEBUG, TAG, "SSID is proper");
                input = input->next;
                continue;
            }
            else {
                OIC_LOG_V(DEBUG, TAG, "SSID is NOT proper");
                goto Error;
            }
        }

        if (OCRepPayloadGetPropString(input, OC_RSRVD_ES_CD, &cd)) {
            if (!strcmp(cd, netProvInfo->netAddressInfo.WIFI.pwd)) {
                OIC_LOG_V(DEBUG, TAG, "Password is proper");
                input = input->next;
                continue;
            }
            else {
                OIC_LOG_V(DEBUG, TAG, "Password is NOT proper");
                goto Error;
            }
        }

        LogProvisioningResponse(input->values);

        input = input->next;

    }

    SuccessCallback(clientResponse);

    return OC_STACK_KEEP_TRANSACTION;

    Error:
    {

        ErrorCallback(DEVICE_NOT_PROVISIONED);

        return OC_STACK_DELETE_TRANSACTION;
    }

}
void LogProvisioningResponse(OCRepPayloadValue * val) {

    switch (val->type) {
        case OCREP_PROP_NULL:
            OIC_LOG_V(DEBUG, TAG, "\t\t%s: NULL", val->name);
            break;
        case OCREP_PROP_INT:
            OIC_LOG_V(DEBUG, TAG, "\t\t%s(int):%lld", val->name, val->i);
            break;
        case OCREP_PROP_DOUBLE:
            OIC_LOG_V(DEBUG, TAG, "\t\t%s(double):%f", val->name, val->d);
            break;
        case OCREP_PROP_BOOL:
            OIC_LOG_V(DEBUG, TAG, "\t\t%s(bool):%s", val->name, val->b ? "true" : "false");
            break;
        case OCREP_PROP_STRING:
            OIC_LOG_V(DEBUG, TAG, "\t\t%s(string):%s", val->name, val->str);
            break;
        case OCREP_PROP_OBJECT:
            // Note: Only prints the URI (if available), to print further, you'll
            // need to dig into the object better!
            OIC_LOG_V(DEBUG, TAG, "\t\t%s(OCRep):%s", val->name, val->obj->uri);
            break;
        case OCREP_PROP_ARRAY:
            switch (val->arr.type) {
                case OCREP_PROP_INT:
                    OIC_LOG_V(DEBUG, TAG, "\t\t%s(int array):%lld x %lld x %lld", val->name,
                              val->arr.dimensions[0], val->arr.dimensions[1],
                              val->arr.dimensions[2]);
                    break;
                case OCREP_PROP_DOUBLE:
                    OIC_LOG_V(DEBUG, TAG, "\t\t%s(double array):%lld x %lld x %lld", val->name,
                              val->arr.dimensions[0], val->arr.dimensions[1],
                              val->arr.dimensions[2]);
                    break;
                case OCREP_PROP_BOOL:
                    OIC_LOG_V(DEBUG, TAG, "\t\t%s(bool array):%lld x %lld x %lld", val->name,
                              val->arr.dimensions[0], val->arr.dimensions[1],
                              val->arr.dimensions[2]);
                    break;
                case OCREP_PROP_STRING:
                    OIC_LOG_V(DEBUG, TAG, "\t\t%s(string array):%lld x %lld x %lld", val->name,
                              val->arr.dimensions[0], val->arr.dimensions[1],
                              val->arr.dimensions[2]);
                    break;
                case OCREP_PROP_OBJECT:
                    OIC_LOG_V(DEBUG, TAG, "\t\t%s(OCRep array):%lld x %lld x %lld", val->name,
                              val->arr.dimensions[0], val->arr.dimensions[1],
                              val->arr.dimensions[2]);
                    break;
                default:
                    break;
            }
            break;
        default:
            break;
    }
}
Esempio n. 30
0
OCStackResult OCConvertPayload(OCPayload* payload, uint8_t** outPayload, size_t* size)
{
    // TinyCbor Version 47a78569c0 or better on master is required for the re-allocation
    // strategy to work.  If you receive the following assertion error, please do a git-pull
    // from the extlibs/tinycbor/tinycbor directory
    #define CborNeedsUpdating  (CborErrorOutOfMemory < CborErrorDataTooLarge)
    OC_STATIC_ASSERT(!CborNeedsUpdating, "tinycbor needs to be updated to at least 47a78569c0");
    #undef CborNeedsUpdating

    OCStackResult ret = OC_STACK_INVALID_PARAM;
    int64_t err;
    uint8_t *out = NULL;
    size_t curSize = INIT_SIZE;

    VERIFY_PARAM_NON_NULL(TAG, payload, "Input param, payload is NULL");
    VERIFY_PARAM_NON_NULL(TAG, outPayload, "OutPayload parameter is NULL");
    VERIFY_PARAM_NON_NULL(TAG, size, "size parameter is NULL");

    OIC_LOG_V(INFO, TAG, "Converting payload of type %d", payload->type);
    if (PAYLOAD_TYPE_SECURITY == payload->type)
    {
        size_t securityPayloadSize = ((OCSecurityPayload *)payload)->payloadSize;
        if (securityPayloadSize > 0)
        {
            out = (uint8_t *)OICCalloc(1, ((OCSecurityPayload *)payload)->payloadSize);
            VERIFY_PARAM_NON_NULL(TAG, out, "Failed to allocate security payload");
        }
    }
    if (out == NULL)
    {
        out = (uint8_t *)OICCalloc(1, curSize);
        VERIFY_PARAM_NON_NULL(TAG, out, "Failed to allocate payload");
    }
    err = OCConvertPayloadHelper(payload, out, &curSize);
    ret = OC_STACK_NO_MEMORY;

    if (err == CborErrorOutOfMemory)
    {
        // reallocate "out" and try again!
        uint8_t *out2 = (uint8_t *)OICRealloc(out, curSize);
        VERIFY_PARAM_NON_NULL(TAG, out2, "Failed to increase payload size");
        out = out2;
        err = OCConvertPayloadHelper(payload, out, &curSize);
        while (err == CborErrorOutOfMemory)
        {
            uint8_t *out2 = (uint8_t *)OICRealloc(out, curSize);
            VERIFY_PARAM_NON_NULL(TAG, out2, "Failed to increase payload size");
            out = out2;
            err = OCConvertPayloadHelper(payload, out, &curSize);
        }
    }

    if (err == CborNoError)
    {
        if (curSize < INIT_SIZE && PAYLOAD_TYPE_SECURITY != payload->type)
        {
            uint8_t *out2 = (uint8_t *)OICRealloc(out, curSize);
            VERIFY_PARAM_NON_NULL(TAG, out2, "Failed to increase payload size");
            out = out2;
        }

        *size = curSize;
        *outPayload = out;
        OIC_LOG_V(DEBUG, TAG, "Payload Size: %zd Payload : ", *size);
        OIC_LOG_BUFFER(DEBUG, TAG, *outPayload, *size);
        return OC_STACK_OK;
    }

    //TODO: Proper conversion from CborError to OCStackResult.
    ret = (OCStackResult)-err;

exit:
    OICFree(out);
    return ret;
}