hosting.c 54.2 KB
Newer Older
1 2
//******************************************************************
//
3
// Copyright 2015 Samsung Electronics All Rights Reserved.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

// Hosting Header
#include "hosting.h"
#include "virtualResource.h"

// External Lib
#include "cJSON.h"

/*
29
 * internal function & static variable
30 31 32
 */
///////////////////////////////////////////////////////////////////////////////////////////////////
static MirrorResourceList *s_mirrorResourceList = NULL;
33
static RequestHandleList *s_requestHandleList = NULL;
34 35 36 37 38

#define OIC_COORDINATING_FLAG "/hosting"
#define OIC_STRING_MAX_VALUE 100

#define OC_DEFAULT_ADDRESS               "224.0.1.187"
39
#define OC_WELL_KNOWN_COORDINATING_QUERY "coap://224.0.1.187:5683/oc/core?rt=Resource.Hosting"
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
#define OC_COORDINATING_QUERY            "/oc/core?rt=Resource.Hosting"
#define DEFAULT_CONTEXT_VALUE 0x99

/*
 * Presence Func for hosting
 */

/**
 *
 * request presence for coordinating
 *
 * @param[in] originResourceAddr - pointer of address string of original resource
 *
 * @return
 *     OC_STACK_OK
 *     OC_STACK_ERROR
 */
OCStackResult requestPresence(char *originResourceAddr);

/**
 *
 * callback function that call when response of presence request received
 *
 * @param[in] originResourceAddr - pointer of address string of original resource
 *
 * @return
 *     OC_STACK_OK
 *     OC_STACK_ERROR
 */
OCStackApplicationResult requestPresenceCB(void *context, OCDoHandle handle,
        OCClientResponse *clientResponse);

/**
 *
 * build mirror resource list by clientResponse
 *
 * @param[in] handle - not using...
 * @param[in] clientResponse - client response that mirror resources are stored
 *
 * @return
 *     pointer of result MirrorResourceList
 */
MirrorResourceList *buildMirrorResourceList(OCDoHandle handle, OCClientResponse *clientResponse);

/**
 *
 * build mirror resource by JSON payload
 *
 * @param[in] ocArray_sub - pointer of json payload string
 *
 * @return
 *     pointer of result MirrorResource
 */
MirrorResource *buildMirrorResource(cJSON *ocArray_sub);

/**
 *
 * This method is used when setting queryUri, registering callback function and starting OCDoResource() Function in order to find Coordinatee Candidate
 *
 * @brief discover coordinatee candidate
 *
 * @return
 *     OC_STACK_OK               - no errors
 *     OC_STACK_INVALID_CALLBACK - invalid callback function pointer
 *     OC_STACK_INVALID_METHOD   - invalid resource method
 *     OC_STACK_INVALID_URI      - invalid required or reference URI
 *     OC_STACK_INVALID_QUERY    - number of resource types specified for filtering presence
 *                                 notifications exceeds @ref MAX_PRESENCE_FILTERS.
 *     OC_STACK_ERROR            - otherwise error(initialized value)
 */
int requestCoordinateeCandidateDiscovery(char *address);

/**
 *
 * This method is used to add a coordinator resource callback method in mirrorResourceList when host resource discovered.
 *
 * @param[in] context
 *              Context for callback method
 * @param[in] handle
 *              Handle to an @ref OCDoResource invocation.
 * @param[in] clientResponse
 *              Response from queries to remote servers. Queries are made by calling the @ref OCDoResource API.
 *
 * @brief callback for receiving response of discoverCoordinateeCandidate()
 *
 * @return
126
 *     PRINT("Callback Context for DISCOVER query recvd successfully")      - context is DEFAULT_CONTEXT_VALUE
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
 *     call the buildMirrorResource() method                                    - clientResponse is not NULL && clientResponse->result is OC_STACK_OK
 *     OC_STACK_KEEP_TRANSACTION                                                - otherwise case
 */
OCStackApplicationResult requestCoordinateeCandidateDiscoveryCB(void *context, OCDoHandle handle,
        OCClientResponse *clientResponse);

/**
 *
 * This method is used when setting queryUri, registering callback function and starting OCDoResource() Function in order to request resource coordination
 *
 * @brief
 *
 * @param[in] mirrorResource
 *          mirrorResource for using in order to request resource coordination
 *
 * @return
 *     OC_STACK_OK               - no errors
 *     OC_STACK_INVALID_CALLBACK - invalid callback function pointer
 *     OC_STACK_INVALID_METHOD   - invalid resource method
 *     OC_STACK_INVALID_URI      - invalid required or reference URI
 *     OC_STACK_INVALID_QUERY    - number of resource types specified for filtering presence
 *                                 notifications exceeds @ref MAX_PRESENCE_FILTERS.
 *     OC_STACK_ERROR            - otherwise error(initialized value)
 */
OCStackResult requestResourceObservation(MirrorResource *mirrorResource);

/**
 *
 * This method is used to handle callback of requestCoordination method.
 *
 * @param[in] context
 *              Context for callback method
 * @param[in] handle
 *              Handle to update mirror resource and check errorResponse
 * @param[in] clientResponse
 *              Response from queries to remote servers. Queries are made by calling the @ref OCDoResource API.
 *
 * @brief callback when receiving response of coordinating requestion.
 *
 * @todo diverge return value
 *
 * @return
 *
 *     OC_STACK_KEEP_TRANSACTION                                            - otherwise case
 */
OCStackApplicationResult requestResourceObservationCB(void *context, OCDoHandle handle,
        OCClientResponse *clientResponse);

/**
 *
 * This method is used to check resource validation and delete resource if it is not exist(not alive).
 *
 * @brief check mirror resource is alive
 *
 * @param[in] requestHandle
 *              Handle to check mirror resource
 *
 * @return
 *
 *     OC_STACK_DELETE_TRANSACTION                                              - otherwise case
 */
OCStackApplicationResult checkResourceValidation(OCDoHandle requestHandle);

/**
 *
 * register Mirror resource in the base resource list
 *
 * @param[in] requestHandle
 *              Handle to check mirror resource
 *
 * @return
 *     OC_STACK_OK
 *     OC_STACK_ERROR
 */
OCStackResult registerMirrorResource(MirrorResource *node);

/**
 *
 * update resource
 *
 * @param[in] sourceHandle - handle of source resource
 * @param[in] payload - pointer of json payload string that update items stored
 *
 * @return
 *     pointer of mirror resource. return NULL if there is any error.
 */
MirrorResource *updateMirrorResource(OCDoHandle sourceHandle, const char *payload);

/**
 *
 * build response payload
 *
 * @param[in] ehRequest - pointer of handler of entity handler request that to be responded
 *
 * @return
 *     OC_STACK_OK
 *     OC_STACK_ERROR
 */
char *buildResponsePayload (OCEntityHandlerRequest *ehRequest);

/**
 *
 * handle "Get" request
 *
 * @param[in] ehRequest - pointer of handler of entity handler request
 * @param[out] payload - pointer of payload to be responded
 * @param[in] maxPayloadSize - size of payload
 *
 * @return
 *     OC_EH_OK - success to copy response payload
 *     OC_EH_ERROR - error to copy response payload
 */
OCEntityHandlerResult handleGetRequest (OCEntityHandlerRequest *ehRequest,
                                        char *payload, uint16_t maxPayloadSize);

/**
 *
 * handle request for non-existing resource
 *
 * @param[in] ehRequest - pointer of handler of entity handler request
 * @param[out] payload - pointer of payload to be responded
 * @param[in] maxPayloadSize - size of payload
 *
 * @return
 *     OC_EH_RESOURCE_DELETED - resource deleted
 */
OCEntityHandlerResult handleNonExistingResourceRequest(OCEntityHandlerRequest *ehRequest,
        char *payload, uint16_t maxPayloadSize);

/**
 *
 * callback function that called when source resource changed
 *
 * @param[in] flag - entity handler flag
 * @param[in] entityHandlerRequest - pointer of entity handler request
 *
 * @return
 *     OC_EH_OK
 *     OC_EH_ERROR
 */
OCEntityHandlerResult resourceEntityHandlerCB (OCEntityHandlerFlag flag,
        OCEntityHandlerRequest *entityHandlerRequest);

/**
 *
 * request that address is alive
 *
 * @param[in] address - pointer of address string
 *
 * @return
 *     OC_STACK_OK
 *     OC_STACK_ERROR
 */
OCStackResult requestIsAlive(const char *address);

/**
 *
 * get string value of OCStackResult code
 *
 * @param[in] result - OCStringResult code
 *
 * @return
 *     pointer of result string value
 */
const char *getResultString(OCStackResult result);

293 294 295 296 297 298 299 300 301
OCStackResult requestQuery(RequestHandle *request, OCMethod method,
                           const char *queryAddress, const char *queryUri);
OCStackApplicationResult requestQueryCB(void *context, OCDoHandle handle,
                                        OCClientResponse *clientResponse);
OCEntityHandlerResponse buildEntityHandlerResponse(OCEntityHandlerRequest *entityHandlerRequest,
        const char *clientPayload);
OCEntityHandlerResult handleRequestPayload (OCEntityHandlerRequest *entityHandlerRequest,
        char *payload, uint16_t maxPayloadSize);

302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
/*
 * for Lite Device Side
 */

/**
 *
 * register resource as coordinatable
 *
 * @param[in] handle - resource handle
 * @param[in] resourceTypeName - resource type name
 * @param[in] resourceInterfaceName - resource interface name
 * @param[in] resourceUri - resource URI
 * @param[in] entityHandler - entity handler
 * @param[in] resourceProperties - resource properties
 *
 * @return
 *     pointer of result string value
 */
OCStackResult registerResourceAsCoordinatable(OCResourceHandle *handle,
        const char *resourceTypeName, const char *resourceInterfaceName,
        const char *resourceUri, OCEntityHandler entityHandler, uint8_t resourceProperties);

OCStackResult registerResourceAsCoordinatable(OCResourceHandle *handle,
        const char *resourceTypeName,
        const char *resourceInterfaceName,
        const char *resourceUri,
        OCEntityHandler entityHandler,
        uint8_t resourceProperties)
{

332 333 334 335 336 337 338
    char *coordinatingURI = (char *)malloc(sizeof(char) *
            (strlen(resourceUri) + strlen(OIC_COORDINATING_FLAG)));
    if(coordinatingURI == NULL)
    {
        OC_LOG_V(DEBUG, HOSTING_TAG, "memory alloc fail : coordinatingURI");
        return OC_STACK_NO_MEMORY;
    }
339

340
    snprintf(coordinatingURI, sizeof(coordinatingURI), "%s%s", resourceUri, OIC_COORDINATING_FLAG);
341

342
    OC_LOG_V(DEBUG, HOSTING_TAG, "requiredUri+coordinatingFlag = %s", coordinatingURI);
343

344 345
    return OCCreateResource(handle, resourceTypeName, resourceInterfaceName,
            coordinatingURI, entityHandler, resourceProperties);
346 347 348 349 350 351 352
}

/*
 *  for Hosting Device Side
 */
OCStackResult OICStartCoordinate()
{
353 354 355 356 357 358 359 360 361 362 363
    OCStackResult ret = OC_STACK_ERROR;
    if (OCInit((char *) NULL, 0, OC_CLIENT_SERVER) != OC_STACK_OK)
    {
        OC_LOG(ERROR, HOSTING_TAG, PCF("OCStack init ERROR"));
    }
    else
    {
        s_mirrorResourceList = createMirrorResourceList();
        s_requestHandleList = createRequestHandleList();
        ret = requestPresence(OC_MULTICAST_PREFIX);
    }
364

365
    return ret;
366 367 368 369 370 371
}

OCStackResult OICStopCoordinate()
{
    OCStackResult result = OC_STACK_ERROR;

372 373 374 375 376
    if (OCStop() == OC_STACK_OK)
    {
        OC_LOG_V(DEBUG, HOSTING_TAG, "OCStack Stop OK");
    }

377
    result = destroyMirrorResourceList(s_mirrorResourceList);
378
    s_mirrorResourceList = NULL;
379 380 381 382
    if(result != OC_STACK_OK)
    {
        return OC_STACK_ERROR;
    }
383 384 385 386 387 388 389 390 391 392 393 394 395 396

    return result;
}

int requestCoordinateeCandidateDiscovery(char *sourceResourceAddress)
{
    OCStackResult result;
    OCCallbackData cbData;
    OCDoHandle handle;

    /* Start a discovery query*/
    char queryUri[OIC_STRING_MAX_VALUE] = { '\0' };
    if (sourceResourceAddress == NULL)
    {
397
        strncpy(queryUri, OC_WELL_KNOWN_COORDINATING_QUERY, sizeof(queryUri));
398 399 400
    }
    else
    {
401 402
        snprintf(queryUri, sizeof(queryUri), "coap://%s%s",
                sourceResourceAddress , OC_COORDINATING_QUERY);
403 404 405 406 407 408
    }

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

409
    result = OCDoResource(&handle, OC_REST_GET, queryUri, OIC_COORDINATING_FLAG, 0,
410
            OC_TRANSPORT, OC_LOW_QOS, &cbData, NULL, 0);
411 412
    if (result != OC_STACK_OK)
    {
413
        OC_LOG_V(DEBUG, HOSTING_TAG, "OCStack resource error");
414
    }
415 416 417 418
    else
    {
        OC_LOG_V(DEBUG, HOSTING_TAG, "Host Resource Finding...");
    }
419 420 421 422 423
    return result;
}

OCStackResult requestPresence(char *sourceResourceAddress)
{
424
    OCStackResult result = OC_STACK_ERROR;
425 426 427 428 429
    OCCallbackData cbData;
    OCDoHandle handle;

    if (sourceResourceAddress == NULL)
    {
430
        OC_LOG_V(DEBUG, HOSTING_TAG, "SourceResourceAddress is not available.");
431 432 433 434 435 436 437 438
        return result;
    }

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

    char queryUri[OIC_STRING_MAX_VALUE] = { '\0' };
439
    snprintf(queryUri, sizeof(queryUri), "coap://%s%s", sourceResourceAddress , OC_PRESENCE_URI);
440
    OC_LOG_V(DEBUG, HOSTING_TAG, "initializePresenceForCoordinating Query : %s", queryUri);
441

442
    result = OCDoResource(&handle, OC_REST_PRESENCE, queryUri, 0, 0,
443
            OC_TRANSPORT, OC_LOW_QOS, &cbData, NULL, 0);
444 445 446

    if (result != OC_STACK_OK)
    {
447
        OC_LOG_V(DEBUG, HOSTING_TAG, "initializePresenceForCoordinating error");
448 449 450 451 452
        result = OC_STACK_ERROR;
    }
    else
    {
        OC_LOG_V(DEBUG, HOSTING_TAG, "Success initializePresenceForCoordinating");
453 454 455 456 457 458 459 460 461 462 463 464 465 466
    }

    return result;
}

OCStackApplicationResult requestPresenceCB(void *context, OCDoHandle handle,
        OCClientResponse *clientResponse)
{
    uint8_t remoteIpAddress[4];
    uint16_t remotePortNumber;
    char address[OIC_STRING_MAX_VALUE] = { '\0' };

    if (context == (void *) DEFAULT_CONTEXT_VALUE)
    {
467
        OC_LOG_V(DEBUG, HOSTING_TAG, "\tCallback Context for presence CB recv successfully");
468 469 470 471 472 473
    }
    if (clientResponse)
    {
        OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddress,
                            remoteIpAddress + 1, remoteIpAddress + 2, remoteIpAddress + 3);
        OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNumber);
474 475
        OC_LOG_V(DEBUG, HOSTING_TAG, "\tStackResult: %s",  getResultString(clientResponse->result));
        OC_LOG_V(DEBUG, HOSTING_TAG, "\tStackResult: %d",  clientResponse->result);
476
        OC_LOG_V(DEBUG, HOSTING_TAG,
477
                 "\tPresence Device =============> Presence %s @ %d.%d.%d.%d:%d",
478 479 480
                 clientResponse->resJSONPayload, remoteIpAddress[0], remoteIpAddress[1],
                 remoteIpAddress[2], remoteIpAddress[3], remotePortNumber);

481
        snprintf(address, sizeof(address), "%d.%d.%d.%d:%d", remoteIpAddress[0], remoteIpAddress[1],
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
                remoteIpAddress[2], remoteIpAddress[3], remotePortNumber);
        if (clientResponse->result == OC_STACK_OK)
        {
            requestCoordinateeCandidateDiscovery(address);
        }
        if (clientResponse->result == OC_STACK_PRESENCE_STOPPED
            || clientResponse->result == OC_STACK_PRESENCE_TIMEOUT
            || clientResponse->result == OC_STACK_PRESENCE_DO_NOT_HANDLE)
        {
            requestIsAlive(address);
        }

    }
    return OC_STACK_KEEP_TRANSACTION;
}

OCStackApplicationResult requestCoordinateeCandidateDiscoveryCB(void *ctx, OCDoHandle handle,
        OCClientResponse *clientResponse)
{
501
    OC_LOG(DEBUG, HOSTING_TAG, "Found Host Resource");
502
    OCStackResult ret = OC_STACK_DELETE_TRANSACTION;
503 504 505

    if (ctx == (void *) DEFAULT_CONTEXT_VALUE)
    {
506
        OC_LOG(DEBUG, HOSTING_TAG, "Callback Context for DISCOVER query recvd successfully");
507 508 509 510 511 512 513 514 515
    }
    if (clientResponse && clientResponse->result == OC_STACK_OK)
    {
        MirrorResourceList *vList = buildMirrorResourceList(handle, clientResponse);
        if (vList != NULL)
        {

            if (vList->headerNode == NULL)
            {
516
                OC_LOG(DEBUG, HOSTING_TAG, "This Discover Response is empty");
517
                return ret;
518 519 520 521 522 523 524 525
            }

            // register All of VirtualResource
            while (vList->headerNode)
            {
                MirrorResource *mirrorResource = vList->headerNode;
                ret = ejectMirrorResource(vList, mirrorResource);
                mirrorResource->next = NULL;
526 527
                OC_LOG_V(DEBUG, HOSTING_TAG,
                        "register virtual resource uri : %s", mirrorResource->uri);
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
                if (ret != OC_STACK_OK)
                {
                    continue;
                }

                ret = registerMirrorResource(mirrorResource);
                if (ret != OC_STACK_OK)
                {
                    continue;
                }

                ret = insertMirrorResource(s_mirrorResourceList, mirrorResource);
                if (ret != OC_STACK_OK)
                {
                    OCDeleteResource(mirrorResource->resourceHandle[OIC_MIRROR_HANDLE]);
                    continue;
                }
                printMirrorResourceList(s_mirrorResourceList);

                ret = requestResourceObservation(mirrorResource);
                if (ret != OC_STACK_OK)
                {
                    OCDeleteResource(mirrorResource->resourceHandle[OIC_MIRROR_HANDLE]);
                    deleteMirrorResourceFromList(s_mirrorResourceList, mirrorResource);
                    continue;
                }
            }
            destroyMirrorResourceList(vList);
            if (ret != OC_STACK_OK)
            {
558
                return ret;
559 560
            }
        }
561
        ret = OC_STACK_KEEP_TRANSACTION;
562
    }
563
    return ret;
564 565 566 567 568 569 570 571 572 573 574 575 576
}

MirrorResourceList *buildMirrorResourceList(OCDoHandle handle, OCClientResponse *clientResponse)
{

    cJSON *discoveryJson = cJSON_CreateObject();
    discoveryJson = cJSON_Parse((char *)clientResponse->resJSONPayload);

    cJSON *ocArray = cJSON_GetObjectItem(discoveryJson, "oc");
    char *ocArray_str = cJSON_PrintUnformatted(ocArray);

    if ( strstr(ocArray_str, "[{}") == ocArray_str )
    {
577
        OC_LOG_V(DEBUG, HOSTING_TAG, "invalid payload : %s", ocArray_str);
578 579 580 581 582 583 584 585 586 587 588 589 590 591
        cJSON_Delete(discoveryJson);
        return NULL;
    }

    MirrorResourceList *retList = createMirrorResourceList();

    uint8_t remoteIpAddr[4];
    uint16_t remotePortNum;

    OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr,
                        remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3);
    OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNum);

    char sourceaddr[OIC_STRING_MAX_VALUE] = {'\0'};
592
    snprintf(sourceaddr, sizeof(sourceaddr), "%d.%d.%d.%d:%d", remoteIpAddr[0], remoteIpAddr[1],
593 594
            remoteIpAddr[2], remoteIpAddr[3], remotePortNum);

595
    OC_LOG_V(DEBUG, HOSTING_TAG, "Host Device =============> Discovered %s @ %s",
596 597 598
             clientResponse->resJSONPayload, sourceaddr);

    int arraySize = cJSON_GetArraySize(ocArray);
599
    for (int i = 0; i < arraySize; ++i)
600 601 602 603 604 605 606 607
    {
        cJSON *ocArray_sub = cJSON_GetArrayItem(ocArray, i);
        MirrorResource *mirrorResource = buildMirrorResource(ocArray_sub);

        if (mirrorResource == NULL)
        {
            continue;
        }
608 609 610 611 612 613 614 615 616
        mirrorResource->address[OIC_SOURCE_ADDRESS] =
                (char *)malloc(sizeof(char) * OIC_STRING_MAX_VALUE);
        if(mirrorResource->address[OIC_SOURCE_ADDRESS] == NULL)
        {
            OC_LOG_V(DEBUG, HOSTING_TAG, "memory alloc fail : mirrorResource address_source");
            destroyMirrorResource(mirrorResource);
            continue;
        }
        snprintf(mirrorResource->address[OIC_SOURCE_ADDRESS],
jyong2.kim's avatar
jyong2.kim committed
617
                sizeof(char) * OIC_STRING_MAX_VALUE, "%s", sourceaddr);
618

619 620 621 622 623 624 625 626 627
        mirrorResource->address[OIC_MIRROR_ADDRESS] =
                (char *)malloc(sizeof(char) * OIC_STRING_MAX_VALUE);
        if(mirrorResource->address[OIC_MIRROR_ADDRESS] == NULL)
        {
            OC_LOG_V(DEBUG, HOSTING_TAG, "memory alloc fail : mirrorResource address_mirror");
            destroyMirrorResource(mirrorResource);
            continue;
        }
        snprintf(mirrorResource->address[OIC_MIRROR_ADDRESS],
jyong2.kim's avatar
jyong2.kim committed
628
                sizeof(char) * OIC_STRING_MAX_VALUE, "0.0.0.0:00");
629 630 631

        if (OC_STACK_OK != insertMirrorResource(retList, mirrorResource))
        {
632
            OC_LOG_V(DEBUG, HOSTING_TAG, "buildVirtualResourceList : insert resource fail");
633
            destroyMirrorResource(mirrorResource);
634 635 636 637 638 639 640 641 642 643
        }
    }

    cJSON_Delete(discoveryJson);
    return retList;
}

MirrorResource *buildMirrorResource(cJSON *ocArray_sub)
{

644
    MirrorResource *mirrorResource = NULL;
645
    char temp[OIC_STRING_MAX_VALUE] = {'\0'};
646
    strncpy(temp, cJSON_GetObjectItem(ocArray_sub, "href")->valuestring, sizeof(temp));
647 648 649

    if ( strstr(temp, OIC_COORDINATING_FLAG) )
    {
650 651 652 653 654 655
        mirrorResource = createMirrorResource();
        if(mirrorResource == NULL)
        {
            OC_LOG_V(DEBUG, HOSTING_TAG, "memory alloc fail for mirrorResource");
            goto RET_ERROR;
        }
656 657

        mirrorResource->uri = (char *)malloc(sizeof(char) * OIC_STRING_MAX_VALUE);
658 659 660 661 662
        if(mirrorResource->uri == NULL)
        {
            OC_LOG_V(DEBUG, HOSTING_TAG, "memory alloc fail for mirrorResource uri");
            goto RET_ERROR;
        }
663 664
        strncpy(mirrorResource->uri, temp, strlen(temp) - strlen(OIC_COORDINATING_FLAG));
        mirrorResource->uri[strlen(temp) - strlen(OIC_COORDINATING_FLAG)] = '\0';
665
        OC_LOG_V(DEBUG, HOSTING_TAG, "VirtualResource URI : %s", mirrorResource->uri);
666 667 668

        cJSON *inArray_sub = cJSON_GetObjectItem(ocArray_sub, "prop");

669 670
        cJSON *tmpJSON = NULL;
        int sizetemp = 0;
671 672 673 674 675

        tmpJSON = cJSON_GetObjectItem(inArray_sub, "rt");
        sizetemp = cJSON_GetArraySize(tmpJSON);
        mirrorResource->prop.countResourceType = sizetemp;
        mirrorResource->prop.resourceType = (char **)malloc(sizeof(char *)*sizetemp);
676
        if (mirrorResource->prop.resourceType == NULL)
677
        {
678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696
            OC_LOG_V(DEBUG, HOSTING_TAG,
                    "memory alloc fail for mirrorResource number of resourceType");
            goto RET_ERROR;
        }
        else
        {
            for (int k = 0; k < sizetemp; ++k)
            {
                mirrorResource->prop.resourceType[k] =
                        (char *)malloc(sizeof(char) * OIC_STRING_MAX_VALUE);
                if (mirrorResource->prop.resourceType[k] == NULL)
                {
                    OC_LOG_V(DEBUG, HOSTING_TAG,
                            "memory alloc fail for mirrorResource resourceType[n]");
                    goto RET_ERROR;
                }
                memset(mirrorResource->prop.resourceType[k], '\0', OIC_STRING_MAX_VALUE);
                strncpy(mirrorResource->prop.resourceType[k],
                        cJSON_GetArrayItem(tmpJSON, k)->valuestring,
jyong2.kim's avatar
jyong2.kim committed
697
                        sizeof(char) * OIC_STRING_MAX_VALUE);
698
            }
699 700 701 702 703 704
        }

        tmpJSON = cJSON_GetObjectItem(inArray_sub, "if");
        sizetemp = cJSON_GetArraySize(tmpJSON);
        mirrorResource->prop.countInterface = sizetemp;
        mirrorResource->prop.resourceInterfaceName = (char **)malloc(sizeof(char *)*sizetemp);
705
        if (mirrorResource->prop.resourceInterfaceName == NULL)
706
        {
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
            OC_LOG_V(DEBUG, HOSTING_TAG,
                    "memory alloc fail for mirrorResource number of resourceInterfaceName");
            goto RET_ERROR;
        }

        for (int k = 0; k < sizetemp; ++k)
        {
            mirrorResource->prop.resourceInterfaceName[k] =
                    (char *)malloc(sizeof(char) * OIC_STRING_MAX_VALUE);
            if (mirrorResource->prop.resourceInterfaceName[k] == NULL)
            {
                OC_LOG_V(DEBUG, HOSTING_TAG,
                        "memory alloc fail for mirrorResource resourceInterfaceName[n]");
                goto RET_ERROR;
            }

723
            memset(mirrorResource->prop.resourceInterfaceName[k], '\0', OIC_STRING_MAX_VALUE);
724 725
            strncpy(mirrorResource->prop.resourceInterfaceName[k],
                    cJSON_GetArrayItem(tmpJSON, k)->valuestring,
jyong2.kim's avatar
jyong2.kim committed
726
                    sizeof(char) * OIC_STRING_MAX_VALUE);
727 728
        }
    }
729 730 731 732 733 734

    return mirrorResource;

RET_ERROR:
    destroyMirrorResource(mirrorResource);
    return NULL;
735 736 737 738 739 740 741 742 743 744
}

OCStackResult registerMirrorResource(MirrorResource *mirrorResource)
{
    OCStackResult result = OC_STACK_ERROR;

    MirrorResource *foundMirrorResource = findMirrorResourceUsingAddressAndURI(s_mirrorResourceList,
                                          mirrorResource->address[OIC_MIRROR_ADDRESS], OIC_MIRROR_ADDRESS, mirrorResource->uri);
    if (foundMirrorResource != NULL)
    {
745
        OC_LOG_V(DEBUG, HOSTING_TAG, "Already registered resource");
746 747 748 749 750 751 752 753 754 755
        goto RETURN_ERR;
    }

    result = OCCreateResource(&(mirrorResource->resourceHandle[OIC_MIRROR_HANDLE]),
                              mirrorResource->prop.resourceType[0],
                              mirrorResource->prop.resourceInterfaceName[0],
                              mirrorResource->uri,
                              resourceEntityHandlerCB,
                              OC_DISCOVERABLE | OC_OBSERVABLE);

756
    OC_LOG_V(DEBUG, HOSTING_TAG, "created mirror resource Handle : %u",mirrorResource->resourceHandle[OIC_MIRROR_HANDLE]);
757 758 759

    if (result != OC_STACK_OK)
    {
760
        OC_LOG_V(DEBUG, HOSTING_TAG, "error return = %s", getResultString(result));
761 762
        mirrorResource->next = NULL;
        destroyMirrorResource(mirrorResource);
763
        return result;
764 765 766 767 768 769 770
    }

    if (mirrorResource->prop.countResourceType > 1)
    {
        int i = 0;
        for (i = 1; i < mirrorResource->prop.countResourceType; ++i)
        {
771 772 773
            result = OCBindResourceTypeToResource(
                             mirrorResource->resourceHandle[OIC_MIRROR_HANDLE],
                             mirrorResource->prop.resourceType[i]);
774 775
            if (result != OC_STACK_OK)
            {
776
                OC_LOG_V(DEBUG, HOSTING_TAG, "Virtual Resource Registration Fail : BindResourceType");
777 778 779 780 781 782 783 784 785 786
                goto RETURN_ERR;
            }
        }
    }

    if (mirrorResource->prop.countInterface > 1)
    {
        int i = 0;
        for (i = 1; i < mirrorResource->prop.countInterface; ++i)
        {
787 788 789
            result = OCBindResourceInterfaceToResource(
                         mirrorResource->resourceHandle[OIC_MIRROR_HANDLE],
                         mirrorResource->prop.resourceInterfaceName[i]);
790 791
            if (result != OC_STACK_OK)
            {
792 793
                OC_LOG_V(DEBUG, HOSTING_TAG,
                        "Virtual Resource Registration Fail : BindResourceInterfaceName");
794 795 796 797 798
                goto RETURN_ERR;
            }
        }
    }

799 800 801
    OC_LOG_V(DEBUG, HOSTING_TAG, "Mirror Resource Registration Success");
    OC_LOG_V(DEBUG, HOSTING_TAG, "Mirror Resource uri : %s", mirrorResource->uri);
    OC_LOG_V(DEBUG, HOSTING_TAG, "Mirror Resource source address : %s",
802
             mirrorResource->address[OIC_SOURCE_ADDRESS]);
803
    OC_LOG_V(DEBUG, HOSTING_TAG, "Mirror Resource virtual address : %s",
804 805 806 807
             mirrorResource->address[OIC_MIRROR_ADDRESS]);
    return result;

RETURN_ERR:
808 809 810 811
    OCDeleteResource(mirrorResource->resourceHandle[OIC_MIRROR_HANDLE]);
    mirrorResource->next = NULL;
    destroyMirrorResource(mirrorResource);

812 813 814 815 816 817 818 819 820 821 822 823 824
    return result;
}

OCStackResult requestResourceObservation(MirrorResource *mirrorResource)
{
    OCStackResult result;
    OCCallbackData cbData;

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

    char query[OIC_STRING_MAX_VALUE] = {'\0'};
825
    snprintf(query, sizeof(query), "coap://%s%s%s", mirrorResource->address[OIC_SOURCE_ADDRESS], mirrorResource->uri,
826 827 828
            OIC_COORDINATING_FLAG);

    result = OCDoResource(&mirrorResource->resourceHandle[OIC_REQUEST_HANDLE], OC_REST_OBSERVE, query,
829
                          0, NULL, OC_TRANSPORT,
830 831 832 833
                          OC_HIGH_QOS, &cbData, NULL, 0);

    if (result != OC_STACK_OK)
    {
834
        OC_LOG_V(DEBUG, HOSTING_TAG, "OCDoResource returns error %s with method %d",
835 836 837 838 839 840 841 842 843
                 getResultString(result), OC_REST_OBSERVE);
    }

    return result;
}

OCStackApplicationResult requestResourceObservationCB(void *context, OCDoHandle handle,
        OCClientResponse *clientResponse)
{
844 845
    OCStackApplicationResult ret = OC_STACK_DELETE_TRANSACTION;

846 847
    if (context == (void *)DEFAULT_CONTEXT_VALUE)
    {
848
        OC_LOG_V(DEBUG, HOSTING_TAG, "Callback Context for OBS query recvd successfully");
849 850 851 852
    }

    if (clientResponse && clientResponse->result != OC_STACK_OK)
    {
853
        OC_LOG_V(DEBUG, HOSTING_TAG, "observeCB result error = %s",
854 855 856 857
                 getResultString(clientResponse->result));
        return checkResourceValidation(handle);
    }

858
    if (clientResponse && clientResponse->result == OC_STACK_OK)
859 860
    {
        OC_LOG_V(DEBUG, HOSTING_TAG,
861 862 863
                 "<=============Callback Context for OBSERVE notification recvd successfully");
        OC_LOG_V(DEBUG, HOSTING_TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
        OC_LOG_V(DEBUG, HOSTING_TAG, "JSON = %s =============> Obs Response",
864 865
                 clientResponse->resJSONPayload);

866
        MirrorResource *foundMirrorResource = updateMirrorResource(handle, clientResponse->resJSONPayload);
867 868
        if (foundMirrorResource == NULL)
        {
869
            OC_LOG_V(DEBUG, HOSTING_TAG, "Cannot found Mirror Resource : Fail");
870
            return ret;
871 872 873 874 875
        }

        if ( OC_STACK_OK != OCNotifyAllObservers(foundMirrorResource->resourceHandle[OIC_MIRROR_HANDLE],
                OC_HIGH_QOS) )
        {
876
            OC_LOG_V(DEBUG, HOSTING_TAG, "Notify Mirror Resource's Subscriber : Fail");
877 878 879
        }
        else
        {
880
            OC_LOG_V(DEBUG, HOSTING_TAG, "Notify Mirror Resource's Subscriber : Success");
881 882 883 884
        }

        if (clientResponse->sequenceNumber == OC_OBSERVE_REGISTER)
        {
885
            OC_LOG_V(DEBUG, HOSTING_TAG, "This also serves as a registration confirmation");
886 887 888
        }
        else if (clientResponse->sequenceNumber == OC_OBSERVE_DEREGISTER)
        {
889
            OC_LOG_V(DEBUG, HOSTING_TAG, "This also serves as a deregistration confirmation");
890
            return ret;
891 892 893
        }
        else if (clientResponse->sequenceNumber == OC_OBSERVE_NO_OPTION)
        {
894
            OC_LOG_V(DEBUG, HOSTING_TAG, "This also tells you that registration/deregistration failed");
895
            return ret;
896
        }
897
        ret = OC_STACK_KEEP_TRANSACTION;
898
    }
899
    return ret;
900 901 902 903
}

OCStackApplicationResult checkResourceValidation(OCDoHandle handle)
{
904 905
    OCStackApplicationResult ret = OC_STACK_DELETE_TRANSACTION;

906 907
    RequestHandle *foundRequestHandle = findRequestHandle(s_requestHandleList, handle,
                                        OIC_REQUEST_BY_COORDINATOR);
908

909
    if (foundRequestHandle == NULL)
910
    {
911
        OC_LOG_V(DEBUG, HOSTING_TAG, "Not found any request.");
912
        return ret;
913 914
    }

915
    if (foundRequestHandle->isAliveCheck)
916
    {
917 918
        OC_LOG_V(DEBUG, HOSTING_TAG, "This response is Alive Check : Expired resource");
        OCDeleteResource(foundRequestHandle->requestHandle[OIC_REQUEST_BY_CLIENT]);
919
    }
920
    deleteRequestHandleFromList(s_requestHandleList, foundRequestHandle);
921
    return ret;
922 923 924 925 926 927 928 929 930 931
}

MirrorResource *updateMirrorResource(OCDoHandle handle, const char *payload)
{
    MirrorResource *foundMirrorResource = findMirrorResourceUsingHandle(
            s_mirrorResourceList, handle, OIC_REQUEST_HANDLE);

    if (!foundMirrorResource)
    {
        // TODO
932
        OC_LOG_V(DEBUG, HOSTING_TAG, "Cannot found Mirror Resource. In updateMirrorResource");
933 934 935
        return NULL;
    }

936 937
    cJSON *repData = NULL;
    cJSON *observeJson = cJSON_Parse(payload);
938

939 940 941 942 943 944
    if (observeJson)
    {
        cJSON *ocArray = cJSON_GetObjectItem(observeJson, "oc");
        cJSON *ocArray_sub = cJSON_GetArrayItem(ocArray, 0);
        cJSON *tempData = cJSON_GetObjectItem(ocArray_sub, "rep");
        char *temp = cJSON_PrintUnformatted(tempData);
945

946 947 948 949 950 951 952 953 954
        repData = cJSON_Parse(temp);
        if (temp != NULL)
        {
            free(temp);
        }
        cJSON_Delete(observeJson);
    }
    else
    {
955
        OC_LOG_V(DEBUG, HOSTING_TAG, "Mirror resource payload is not correct");
956 957
        return NULL;
    }
958 959 960 961 962 963 964 965 966 967 968

    if (foundMirrorResource->rep)
    {
        cJSON_Delete(foundMirrorResource->rep);
        foundMirrorResource->rep = NULL;
    }
    foundMirrorResource->rep = repData;

    cJSON *json = cJSON_CreateObject();

    char nodeData[OIC_STRING_MAX_VALUE] = {'\0'};
969
    snprintf(nodeData, sizeof(foundMirrorResource->uri), "%s", foundMirrorResource->uri);
970 971 972 973
    cJSON_AddStringToObject(json, "href", nodeData);

    cJSON *nodeRep = cJSON_Parse(cJSON_PrintUnformatted(foundMirrorResource->rep));
    cJSON_AddItemToObject(json, "rep", nodeRep);
974
    OC_LOG_V(DEBUG, HOSTING_TAG, "It will notify resource : %s", cJSON_PrintUnformatted(json));
975 976 977 978 979 980 981 982 983 984 985 986

    cJSON_Delete(json);

    return foundMirrorResource;
}

char *buildResponsePayload (OCEntityHandlerRequest *entityHandlerRequest)
{
    MirrorResource *mirrorResource = findMirrorResourceUsingHandle(s_mirrorResourceList,
                                     entityHandlerRequest->resource, OIC_MIRROR_HANDLE);
    if (!mirrorResource)
    {
987 988
        OC_LOG_V(DEBUG, HOSTING_TAG, "Cannot found Mirror Resource. In buildResponsePayload()");
        OC_LOG_V(DEBUG, HOSTING_TAG, "Mirror Resource's Handle : %x.", entityHandlerRequest->resource);
989 990 991
        return NULL;
    }

992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
    if (entityHandlerRequest->method == OC_REST_PUT)
    {
        OC_LOG_V(DEBUG, HOSTING_TAG, "oc_rest_put");
        if (mirrorResource->rep)
        {
            cJSON_Delete(mirrorResource->rep);
            mirrorResource->rep = NULL;
        }
        mirrorResource->rep = cJSON_CreateObject();
        mirrorResource->rep = cJSON_Parse(entityHandlerRequest->reqJSONPayload);
    }

    OC_LOG_V(DEBUG, HOSTING_TAG, "node's uri : %s", mirrorResource->uri);
    OC_LOG_V(DEBUG, HOSTING_TAG, "node's source address : %s", mirrorResource->address[0]);
    OC_LOG_V(DEBUG, HOSTING_TAG, "node's mirror address : %s", mirrorResource->address[1]);
    OC_LOG_V(DEBUG, HOSTING_TAG, "node's rep : %s", cJSON_PrintUnformatted(mirrorResource->rep));
1008 1009 1010 1011

    cJSON *jsonObject = cJSON_CreateObject();

    char uriString[OIC_STRING_MAX_VALUE] = {'\0'};
1012
    snprintf(uriString, sizeof(uriString), "%s", mirrorResource->uri);
1013 1014 1015 1016
    cJSON_AddStringToObject(jsonObject, "href", uriString);

    cJSON *itemRep = cJSON_Parse(cJSON_PrintUnformatted(mirrorResource->rep));
    cJSON_AddItemToObject(jsonObject, "rep", itemRep);
1017
    OC_LOG_V(DEBUG, HOSTING_TAG, "Will response resource : %s", cJSON_PrintUnformatted(jsonObject));
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028

    char *jsonResponse = cJSON_Print(jsonObject);
    cJSON_Delete(jsonObject);

    return jsonResponse;
}

OCEntityHandlerResult
resourceEntityHandlerCB (OCEntityHandlerFlag entifyHandlerFlag,
                         OCEntityHandlerRequest *entityHandlerRequest)
{
1029
    OC_LOG_V(DEBUG, HOSTING_TAG, "Inside device default entity handler - flags: 0x%x",
1030 1031 1032 1033 1034 1035 1036 1037 1038
             entifyHandlerFlag);

    OCEntityHandlerResult entityHandlerResult = OC_EH_OK;
    OCEntityHandlerResponse entityHandlerResponse;
    char payload[MAX_RESPONSE_LENGTH] = {0};

    // Validate pointer
    if (!entityHandlerRequest)
    {
1039
        OC_LOG_V(DEBUG, HOSTING_TAG, "Invalid request pointer");
1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
        return OC_EH_ERROR;
    }

    // Initialize certain response fields
    entityHandlerResponse.numSendVendorSpecificHeaderOptions = 0;
    memset(entityHandlerResponse.sendVendorSpecificHeaderOptions, 0,
           sizeof entityHandlerResponse.sendVendorSpecificHeaderOptions);
    memset(entityHandlerResponse.resourceUri, 0, sizeof entityHandlerResponse.resourceUri);

    if (entifyHandlerFlag & OC_REQUEST_FLAG)
    {
1051
        OC_LOG_V(DEBUG, HOSTING_TAG, "Flag includes OC_REQUEST_FLAG");
1052 1053
        if (entityHandlerRequest->resource == NULL)
        {
1054
            OC_LOG_V(DEBUG, HOSTING_TAG, "Received request from client to a non-existing resource");
1055 1056 1057 1058 1059
            entityHandlerResult = handleNonExistingResourceRequest(entityHandlerRequest, payload,
                                  sizeof(payload) - 1);
        }
        else if (OC_REST_GET == entityHandlerRequest->method)
        {
1060
            OC_LOG_V(DEBUG, HOSTING_TAG, "Received OC_REST_GET from client");
1061 1062
            entityHandlerResult = handleGetRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
        }
1063 1064
        else if (OC_REST_PUT == entityHandlerRequest->method ||
                 OC_REST_DELETE == entityHandlerRequest->method )
1065
        {
1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
            OC_LOG_V(DEBUG, HOSTING_TAG, "Received OC_REST_PUT/DELETE from client");

            RequestHandle *request = createRequestHandle();

            request->requestHandle[OIC_REQUEST_BY_CLIENT] = entityHandlerRequest;
            request->resourceHandle = entityHandlerRequest->resource;
            request->method = entityHandlerRequest->method;
            request->entityRequestHandle = entityHandlerRequest->requestHandle;

            OCStackResult result = insertRequestHandle(s_requestHandleList, request);
            if (result != OC_STACK_OK)
            {
                OC_LOG_V(DEBUG, HOSTING_TAG, "Insert request list : fail2(%d)", result);
                return result;
            }

            MirrorResource *mirrorResource = findMirrorResourceUsingHandle(s_mirrorResourceList,
                                             entityHandlerRequest->resource, OIC_MIRROR_HANDLE);
            if (mirrorResource == NULL)
            {
                OC_LOG_V(DEBUG, HOSTING_TAG, "Not found requested resource");
                return OC_EH_ERROR;
            }

            result = requestQuery(request,
                    entityHandlerRequest->method, mirrorResource->address[OIC_SOURCE_ADDRESS],
                    mirrorResource->uri);
            if (result != OC_STACK_OK)
            {
1095
                OC_LOG_V(DEBUG, HOSTING_TAG, "Request query failed");
1096 1097 1098
                deleteRequestHandleFromList(s_requestHandleList, request);
            }
            return OC_EH_OK;
1099 1100 1101
        }
        else
        {
1102
            OC_LOG_V(DEBUG, HOSTING_TAG, "Received unsupported method %d from client",
1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
                     entityHandlerRequest->method);
            entityHandlerResult = OC_EH_ERROR;
        }

        // If the result isn't an error or forbidden, send response
        if (!((entityHandlerResult == OC_EH_ERROR) || (entityHandlerResult == OC_EH_FORBIDDEN)))
        {
            // Format the response.  Note this requires some info about the request
            entityHandlerResponse.requestHandle = entityHandlerRequest->requestHandle;
            entityHandlerResponse.resourceHandle = entityHandlerRequest->resource;
            entityHandlerResponse.ehResult = entityHandlerResult;
1114
            entityHandlerResponse.payload = (char *)payload;
1115 1116 1117 1118 1119 1120 1121 1122
            entityHandlerResponse.payloadSize = strlen(payload);
            // Indicate that response is NOT in a persistent buffer
            entityHandlerResponse.persistentBufferFlag = 0;

            // Handle vendor specific options
            if (entityHandlerRequest->rcvdVendorSpecificHeaderOptions &&
                entityHandlerRequest->numRcvdVendorSpecificHeaderOptions)
            {
1123
                OC_LOG_V(DEBUG, HOSTING_TAG, "Received vendor specific options");
1124 1125
                OCHeaderOption *receivedVenderSpecificHeaderOptions =
                    entityHandlerRequest->rcvdVendorSpecificHeaderOptions;
1126
                for ( int i = 0; i < entityHandlerRequest->numRcvdVendorSpecificHeaderOptions; i++)
1127 1128 1129
                {
                    if (((OCHeaderOption)receivedVenderSpecificHeaderOptions[i]).protocolID == OC_COAP_ID)
                    {
1130
                        OC_LOG_V(DEBUG, HOSTING_TAG, "Received option with OC_COAP_ID and ID %u with",
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
                                 ((OCHeaderOption)receivedVenderSpecificHeaderOptions[i]).optionID );
                    }
                }
                OCHeaderOption *sendVenderSpecificHeaderOptions =
                    entityHandlerResponse.sendVendorSpecificHeaderOptions;
                uint8_t option2[] = {21, 22, 23, 24, 25, 26, 27, 28, 29, 30};
                uint8_t option3[] = {31, 32, 33, 34, 35, 36, 37, 38, 39, 40};
                sendVenderSpecificHeaderOptions[0].protocolID = OC_COAP_ID;
                sendVenderSpecificHeaderOptions[0].optionID = 2248;
                memcpy(sendVenderSpecificHeaderOptions[0].optionData, option2, sizeof(option2));
                sendVenderSpecificHeaderOptions[0].optionLength = 10;
                sendVenderSpecificHeaderOptions[1].protocolID = OC_COAP_ID;
                sendVenderSpecificHeaderOptions[1].optionID = 2600;
                memcpy(sendVenderSpecificHeaderOptions[1].optionData, option3, sizeof(option3));
                sendVenderSpecificHeaderOptions[1].optionLength = 10;
                entityHandlerResponse.numSendVendorSpecificHeaderOptions = 2;
            }

            // Send the response
            if (OCDoResponse(&entityHandlerResponse) != OC_STACK_OK)
            {
                OC_LOG(ERROR, HOSTING_TAG, "Error sending response");
                entityHandlerResult = OC_EH_ERROR;
            }
        }
    }
    if (entifyHandlerFlag & OC_OBSERVE_FLAG)
    {
1159
        OC_LOG_V(DEBUG, HOSTING_TAG, "Flag includes OC_OBSERVE_FLAG");
1160 1161
        if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action)
        {
1162
            OC_LOG_V(DEBUG, HOSTING_TAG, "Received OC_OBSERVE_REGISTER from client");
1163 1164 1165
        }
        else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action)
        {
1166
            OC_LOG_V(DEBUG, HOSTING_TAG, "Received OC_OBSERVE_DEREGISTER from client");
1167 1168 1169 1170 1171
        }
    }

    return entityHandlerResult;
}
1172 1173 1174
OCEntityHandlerResult
handleGetRequest (OCEntityHandlerRequest *entityHandlerRequest,
        char *payload, uint16_t maxPayloadSize)
1175
{
1176
    OC_LOG_V(DEBUG, HOSTING_TAG, "ProcessGetRequest in....");
1177

1178
    OCEntityHandlerResult entityHandlerResult = OC_EH_ERROR;
1179
    char *responsePayload = buildResponsePayload(entityHandlerRequest);
1180 1181
    if(!responsePayload)
    {
1182
        return entityHandlerResult;
1183
    }
1184 1185 1186 1187 1188 1189 1190 1191

    if (maxPayloadSize > strlen ((char *)responsePayload))
    {
        strncpy(payload, responsePayload, strlen((char *)responsePayload));
        entityHandlerResult = OC_EH_OK;
    }
    else
    {
1192
        OC_LOG_V(DEBUG, HOSTING_TAG, "Response buffer: %d bytes is too small", maxPayloadSize);
1193 1194 1195 1196 1197 1198
    }

    free(responsePayload);

    return entityHandlerResult;
}
1199 1200
OCEntityHandlerResult
handleNonExistingResourceRequest(OCEntityHandlerRequest *entityHandlerRequest,
1201 1202
        char *payload, uint16_t maxPayloadSize)
{
1203
    OC_LOG_V(INFO, HOSTING_TAG, "Executing %s ", __func__);
1204

1205 1206 1207
    char responsePayload[OIC_STRING_MAX_VALUE] = {'\0'};
    strncpy(responsePayload, "{App determines payload: The resource does not exist.}",
            sizeof(responsePayload));
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229

    if ( (entityHandlerRequest != NULL) &&
         (maxPayloadSize > strlen ((char *)responsePayload)) )
    {
        strncpy((char *)payload, responsePayload, strlen((char *)responsePayload));
    }
    else
    {
        OC_LOG_V (INFO, HOSTING_TAG, "Response buffer: %d bytes is too small",
                  maxPayloadSize);
    }

    return OC_EH_RESOURCE_DELETED;
}

OCStackResult requestIsAlive(const char *address)
{
    MirrorResourceList *requestMirrorResourceList = findMirrorResourceListUsingAddress(
                s_mirrorResourceList, address, OIC_SOURCE_ADDRESS);

    if (requestMirrorResourceList == NULL)
    {
1230
        OC_LOG_V(DEBUG, HOSTING_TAG, "Cannot found any mirror resource1");
1231 1232 1233 1234 1235
        return OC_STACK_ERROR;
    }

    if (requestMirrorResourceList->headerNode == NULL)
    {
1236
        OC_LOG_V(DEBUG, HOSTING_TAG, "Cannot found any mirror resource2");
1237 1238 1239 1240 1241 1242
        return OC_STACK_ERROR;
    }

    MirrorResource *mirrorResource = requestMirrorResourceList->headerNode;
    while (mirrorResource)
    {
1243 1244 1245 1246 1247 1248 1249
        RequestHandle *requestAlive = createRequestHandle();
        requestAlive->isAliveCheck = 1;
        requestAlive->requestHandle[OIC_REQUEST_BY_CLIENT] =
            mirrorResource->resourceHandle[OIC_MIRROR_HANDLE];

        OCStackResult result = insertRequestHandle(s_requestHandleList, requestAlive);
        if (result != OC_STACK_OK)
1250
        {
1251 1252
            OC_LOG_V(DEBUG, HOSTING_TAG, "Insert request list : fail3");
            return result;
1253 1254
        }

1255
        result = requestQuery(requestAlive, OC_REST_GET, address, mirrorResource->uri);
1256 1257
        if (result != OC_STACK_OK)
        {
1258
            deleteRequestHandleFromList(s_requestHandleList, requestAlive);
1259
        }
1260
        mirrorResource = mirrorResource->next;
1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323
    }
    destroyMirrorResourceList(requestMirrorResourceList);

    return OC_STACK_OK;
}

const char *getResultString(OCStackResult result)
{
    switch (result)
    {
        case OC_STACK_OK:
            return "OC_STACK_OK";
        case OC_STACK_RESOURCE_CREATED:
            return "OC_STACK_RESOURCE_CREATED";
        case OC_STACK_RESOURCE_DELETED:
            return "OC_STACK_RESOURCE_DELETED";
        case OC_STACK_INVALID_URI:
            return "OC_STACK_INVALID_URI";
        case OC_STACK_INVALID_QUERY:
            return "OC_STACK_INVALID_QUERY";
        case OC_STACK_INVALID_IP:
            return "OC_STACK_INVALID_IP";
        case OC_STACK_INVALID_PORT:
            return "OC_STACK_INVALID_PORT";
        case OC_STACK_INVALID_CALLBACK:
            return "OC_STACK_INVALID_CALLBACK";
        case OC_STACK_INVALID_METHOD:
            return "OC_STACK_INVALID_METHOD";
        case OC_STACK_NO_MEMORY:
            return "OC_STACK_NO_MEMORY";
        case OC_STACK_COMM_ERROR:
            return "OC_STACK_COMM_ERROR";
        case OC_STACK_INVALID_PARAM:
            return "OC_STACK_INVALID_PARAM";
        case OC_STACK_NOTIMPL:
            return "OC_STACK_NOTIMPL";
        case OC_STACK_NO_RESOURCE:
            return "OC_STACK_NO_RESOURCE";
        case OC_STACK_RESOURCE_ERROR:
            return "OC_STACK_RESOURCE_ERROR";
        case OC_STACK_SLOW_RESOURCE:
            return "OC_STACK_SLOW_RESOURCE";
        case OC_STACK_NO_OBSERVERS:
            return "OC_STACK_NO_OBSERVERS";
        case OC_STACK_VIRTUAL_DO_NOT_HANDLE:
            return "OC_STACK_VIRTUAL_DO_NOT_HANDLE";
        case OC_STACK_PRESENCE_STOPPED:
            return "OC_STACK_PRESENCE_STOPPED";
        case OC_STACK_PRESENCE_TIMEOUT:
            return "OC_STACK_PRESENCE_TIMEOUT";
        case OC_STACK_PRESENCE_DO_NOT_HANDLE:
            return "OC_STACK_PRESENCE_DO_NOT_HANDLE";
        case OC_STACK_ERROR:
            return "OC_STACK_ERROR";
        default:
            return "UNKNOWN";
    }
}

void getJsonArrayPair(cJSON *tempData)
{
    int countofrep = cJSON_GetArraySize(tempData);
    OC_LOG_V(DEBUG, HOSTING_TAG,
1324 1325 1326
             "//////////////////////////////////////////////////////////////////////////");
    OC_LOG_V(DEBUG, HOSTING_TAG, "//Test");
    OC_LOG_V(DEBUG, HOSTING_TAG, "rep Size : %d", countofrep);
1327 1328

    for (int i = 0; i < countofrep; ++i)
1329 1330
    {
        cJSON *arrayJSON = cJSON_GetArrayItem(tempData, i);
1331
        OC_LOG_V(DEBUG, HOSTING_TAG, "rep#%d's name : %s", i, arrayJSON->string);
1332 1333 1334 1335 1336

        switch (arrayJSON->type)
        {
            case cJSON_False:
            case cJSON_True:
1337
                OC_LOG_V(DEBUG, HOSTING_TAG, "rep#%d's value : %d", i, arrayJSON->valueint);
1338 1339
                break;
            case cJSON_Number:
1340
                OC_LOG_V(DEBUG, HOSTING_TAG, "rep#%d's value : %f", i, arrayJSON->valuedouble);
1341 1342
                break;
            case cJSON_String: