Merge branch 'master' into windows-port
[platform/upstream/iotivity.git] / resource / csdk / security / provisioning / src / pmutility.c
1 /* *****************************************************************
2  *
3  * Copyright 2015 Samsung Electronics All Rights Reserved.
4  *
5  *
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *     http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  * *****************************************************************/
20 #ifndef _POSIX_C_SOURCE
21 #define _POSIX_C_SOURCE 200112L
22 #endif
23
24 #if HAVE_UNISTD_H
25 #include <unistd.h>
26 #endif
27 #ifdef HAVE_WINDOWS_H
28 #include <windows.h>
29 #endif
30 #ifdef HAVE_STRING_H
31 #include <string.h>
32 #endif
33 #ifdef HAVE_TIME_H
34 #include <time.h>
35 #endif
36 #ifdef HAVE_SYS_TIME_H
37 #include <sys/time.h>
38 #endif
39
40 #include "ocstack.h"
41 #include "oic_malloc.h"
42 #include "oic_string.h"
43 #include "logger.h"
44 #include "cJSON.h"
45 #include "utlist.h"
46 #include "ocpayload.h"
47
48 #include "securevirtualresourcetypes.h"
49 #include "srmresourcestrings.h" //@note: SRM's internal header
50 #include "doxmresource.h"       //@note: SRM's internal header
51 #include "pstatresource.h"      //@note: SRM's internal header
52 #include "verresource.h"      //@note: SRM's internal header
53
54 #include "pmtypes.h"
55 #include "pmutility.h"
56
57 #include "srmutility.h"
58
59 #define TAG ("PM-UTILITY")
60
61 typedef struct _DiscoveryInfo{
62     OCProvisionDev_t    **ppDevicesList;
63     bool                isOwnedDiscovery;
64 } DiscoveryInfo;
65
66 /*
67  * Function to discover secre port information through unicast
68  *
69  * @param[in] discoveryInfo The pointer of discovery information to matain result of discovery
70  * @param[in] clientResponse  Response information(It will contain payload)
71  *
72  * @return OC_STACK_OK on success otherwise error.
73  */
74 static OCStackResult SecurePortDiscovery(DiscoveryInfo* discoveryInfo,
75                                          const OCClientResponse *clientResponse);
76
77 /*
78  * Function to discover security version information through unicast
79  *
80  * @param[in] discoveryInfo The pointer of discovery information to matain result of discovery
81  * @param[in] clientResponse  Response information(It will contain payload)
82  *
83  * @return OC_STACK_OK on success otherwise error.
84  */
85 static OCStackResult SecurityVersionDiscovery(DiscoveryInfo* discoveryInfo,
86                                               const OCClientResponse *clientResponse);
87
88 /**
89  * Callback handler for PMDeviceDiscovery API.
90  *
91  * @param[in] ctx             User context
92  * @param[in] handle          Handler for response
93  * @param[in] clientResponse  Response information (It will contain payload)
94  * @return OC_STACK_KEEP_TRANSACTION to keep transaction and
95  *         OC_STACK_DELETE_TRANSACTION to delete it.
96  */
97 static OCStackApplicationResult DeviceDiscoveryHandler(void *ctx, OCDoHandle UNUSED,
98                                 OCClientResponse *clientResponse);
99
100 /**
101  * Callback handler for getting secure port information using /oic/res discovery.
102  *
103  * @param[in] ctx             user context
104  * @param[in] handle          Handle for response
105  * @param[in] clientResponse  Response information(It will contain payload)
106  *
107  * @return OC_STACK_KEEP_TRANSACTION to keep transaction and
108  *         OC_STACK_DELETE_TRANSACTION to delete it.
109  */
110 static OCStackApplicationResult SecurePortDiscoveryHandler(void *ctx, OCDoHandle UNUSED,
111                                  OCClientResponse *clientResponse);
112
113 /**
114  * Callback handler for security version discovery.
115  *
116  * @param[in] ctx             User context
117  * @param[in] handle          Handler for response
118  * @param[in] clientResponse  Response information (It will contain payload)
119  * @return OC_STACK_KEEP_TRANSACTION to keep transaction and
120  *         OC_STACK_DELETE_TRANSACTION to delete it.
121  */
122 static OCStackApplicationResult SecVersionDiscoveryHandler(void *ctx, OCDoHandle UNUSED,
123                                 OCClientResponse *clientResponse);
124
125 /**
126  * Function to search node in linked list that matches given IP and port.
127  *
128  * @param[in] pList         List of OCProvisionDev_t.
129  * @param[in] addr          address of target device.
130  * @param[in] port          port of remote server.
131  *
132  * @return pointer of OCProvisionDev_t if exist, otherwise NULL
133  */
134 OCProvisionDev_t* GetDevice(OCProvisionDev_t **ppDevicesList, const char* addr, const uint16_t port)
135 {
136     if(NULL == addr || NULL == *ppDevicesList)
137     {
138         OIC_LOG_V(ERROR, TAG, "Invalid Input parameters in [%s]\n", __FUNCTION__);
139         return NULL;
140     }
141
142     OCProvisionDev_t *ptr = NULL;
143     LL_FOREACH(*ppDevicesList, ptr)
144     {
145         if( strcmp(ptr->endpoint.addr, addr) == 0 && port == ptr->endpoint.port)
146         {
147             return ptr;
148         }
149     }
150
151     return NULL;
152 }
153
154
155 /**
156  * Add device information to list.
157  *
158  * @param[in] pList         List of OCProvisionDev_t.
159  * @param[in] addr          address of target device.
160  * @param[in] port          port of remote server.
161  * @param[in] adapter       adapter type of endpoint.
162  * @param[in] doxm          pointer to doxm instance.
163  * @param[in] connType  connectivity type of endpoint
164  *
165  * @return OC_STACK_OK for success and errorcode otherwise.
166  */
167 OCStackResult AddDevice(OCProvisionDev_t **ppDevicesList, const char* addr, const uint16_t port,
168                         OCTransportAdapter adapter, OCConnectivityType connType, OicSecDoxm_t *doxm)
169 {
170     if (NULL == addr)
171     {
172         return OC_STACK_INVALID_PARAM;
173     }
174
175     OCProvisionDev_t *ptr = GetDevice(ppDevicesList, addr, port);
176     if(!ptr)
177     {
178         ptr = (OCProvisionDev_t *)OICCalloc(1, sizeof (OCProvisionDev_t));
179         if (NULL == ptr)
180         {
181             OIC_LOG(ERROR, TAG, "Error while allocating memory for linkedlist node !!");
182             return OC_STACK_NO_MEMORY;
183         }
184
185         OICStrcpy(ptr->endpoint.addr, MAX_ADDR_STR_SIZE, addr);
186         ptr->endpoint.port = port;
187         ptr->doxm = doxm;
188         ptr->securePort = DEFAULT_SECURE_PORT;
189         ptr->endpoint.adapter = adapter;
190         ptr->next = NULL;
191         ptr->connType = connType;
192         ptr->devStatus = DEV_STATUS_ON; //AddDevice is called when discovery(=alive)
193         OICStrcpy(ptr->secVer, MAX_VERSION_LEN, DEFAULT_SEC_VERSION); // version initialization
194
195         LL_PREPEND(*ppDevicesList, ptr);
196     }
197
198     return OC_STACK_OK;
199 }
200
201 /**
202  * Function to set secure port information from the given list of devices.
203  *
204  * @param[in] pList         List of OCProvisionDev_t.
205  * @param[in] addr          address of target device.
206  * @param[in] port          port of remote server.
207  * @param[in] secureport    secure port information.
208  *
209  * @return OC_STACK_OK for success and errorcode otherwise.
210  */
211 OCStackResult UpdateSecurePortOfDevice(OCProvisionDev_t **ppDevicesList, const char *addr,
212                                        uint16_t port, uint16_t securePort)
213 {
214     OCProvisionDev_t *ptr = GetDevice(ppDevicesList, addr, port);
215
216     if(!ptr)
217     {
218         OIC_LOG(ERROR, TAG, "Can not find device information in the discovery device list");
219         return OC_STACK_ERROR;
220     }
221
222     ptr->securePort = securePort;
223
224     return OC_STACK_OK;
225 }
226
227 /**
228  * Function to set security version information from the given list of devices.
229  *
230  * @param[in] pList         List of OCProvisionDev_t.
231  * @param[in] addr          address of target device.
232  * @param[in] port          port of remote server.
233  * @param[in] secVer    security version information.
234  *
235  * @return OC_STACK_OK for success and errorcode otherwise.
236  */
237 OCStackResult UpdateSecVersionOfDevice(OCProvisionDev_t **ppDevicesList, const char *addr,
238                                        uint16_t port, const char* secVer)
239 {
240     if (NULL == secVer)
241     {
242         return OC_STACK_INVALID_PARAM;
243     }
244
245     OCProvisionDev_t *ptr = GetDevice(ppDevicesList, addr, port);
246
247     if(!ptr)
248     {
249         OIC_LOG(ERROR, TAG, "Can not find device information in the discovery device list");
250         return OC_STACK_ERROR;
251     }
252
253     OICStrcpy(ptr->secVer, MAX_VERSION_LEN, secVer);
254
255     return OC_STACK_OK;
256 }
257
258 /**
259  * This function deletes list of provision target devices
260  *
261  * @param[in] pDevicesList         List of OCProvisionDev_t.
262  */
263 void PMDeleteDeviceList(OCProvisionDev_t *pDevicesList)
264 {
265     if(pDevicesList)
266     {
267         OCProvisionDev_t *del = NULL, *tmp = NULL;
268         LL_FOREACH_SAFE(pDevicesList, del, tmp)
269         {
270             LL_DELETE(pDevicesList, del);
271
272             DeleteDoxmBinData(del->doxm);
273             DeletePstatBinData(del->pstat);
274             OICFree(del);
275         }
276     }
277 }
278
279 OCProvisionDev_t* PMCloneOCProvisionDev(const OCProvisionDev_t* src)
280 {
281     OIC_LOG(DEBUG, TAG, "IN PMCloneOCProvisionDev");
282
283     if (!src)
284     {
285         OIC_LOG(ERROR, TAG, "PMCloneOCProvisionDev : Invalid parameter");
286         return NULL;
287     }
288
289     // TODO: Consider use VERIFY_NON_NULL instead of if ( null check ) { goto exit; }
290     OCProvisionDev_t* newDev = (OCProvisionDev_t*)OICCalloc(1, sizeof(OCProvisionDev_t));
291     VERIFY_NON_NULL(TAG, newDev, ERROR);
292
293     memcpy(&newDev->endpoint, &src->endpoint, sizeof(OCDevAddr));
294
295     if (src->pstat)
296     {
297         newDev->pstat= (OicSecPstat_t*)OICCalloc(1, sizeof(OicSecPstat_t));
298         VERIFY_NON_NULL(TAG, newDev->pstat, ERROR);
299
300         memcpy(newDev->pstat, src->pstat, sizeof(OicSecPstat_t));
301         // We have to assign NULL for not necessary information to prevent memory corruption.
302         newDev->pstat->sm = NULL;
303     }
304
305     if (src->doxm)
306     {
307         newDev->doxm = (OicSecDoxm_t*)OICCalloc(1, sizeof(OicSecDoxm_t));
308         VERIFY_NON_NULL(TAG, newDev->doxm, ERROR);
309
310         memcpy(newDev->doxm, src->doxm, sizeof(OicSecDoxm_t));
311         // We have to assign NULL for not necessary information to prevent memory corruption.
312         newDev->doxm->oxmType = NULL;
313         newDev->doxm->oxm = NULL;
314     }
315
316     if (0 == strlen(src->secVer))
317     {
318         OICStrcpy(newDev->secVer, MAX_VERSION_LEN, DEFAULT_SEC_VERSION);
319     }
320     else
321     {
322         OICStrcpy(newDev->secVer, MAX_VERSION_LEN, src->secVer);
323     }
324
325     newDev->securePort = src->securePort;
326     newDev->devStatus = src->devStatus;
327     newDev->connType = src->connType;
328     newDev->next = NULL;
329
330     OIC_LOG(DEBUG, TAG, "OUT PMCloneOCProvisionDev");
331
332     return newDev;
333
334 exit:
335     OIC_LOG(ERROR, TAG, "PMCloneOCProvisionDev : Failed to allocate memory");
336     if (newDev)
337     {
338         OICFree(newDev->pstat);
339         OICFree(newDev->doxm);
340         OICFree(newDev);
341     }
342     return NULL;
343 }
344
345 /**
346  * Timeout implementation for secure discovery. When performing secure discovery,
347  * we should wait a certain period of time for getting response of each devices.
348  *
349  * @param[in]  waittime  Timeout in seconds.
350  * @param[in]  waitForStackResponse if true timeout function will call OCProcess while waiting.
351  * @return OC_STACK_OK on success otherwise error.
352  */
353 OCStackResult PMTimeout(unsigned short waittime, bool waitForStackResponse)
354 {
355     OCStackResult res = OC_STACK_OK;
356 #if defined(HAVE_GETSYSTEMTIMEASFILETIME)
357     FILETIME startTime = {0};
358     FILETIME currTime = {0};
359
360     GetSystemTimeAsFileTime(&startTime);
361 #elif defined(HAVE_CLOCK_GETTIME)
362     struct timespec startTime = {.tv_sec=0, .tv_nsec=0};
363     struct timespec currTime  = {.tv_sec=0, .tv_nsec=0};
364
365 # if defined(_POSIX_MONOTONIC_CLOCK)
366     int clock_res = clock_gettime(CLOCK_MONOTONIC, &startTime);
367 # else
368     int clock_res = clock_gettime(CLOCK_REALTIME, &startTime);
369 # endif // defined(_POSIX_MONOTONIC_CLOCK)
370     if (0 != clock_res)
371     {
372         return OC_STACK_ERROR;
373     }
374
375 #else
376     ERROR Need PMTimeout implementation
377     return OC_STACK_ERROR;
378 #endif
379
380     while (OC_STACK_OK == res)
381     {
382 #if defined(HAVE_GETSYSTEMTIMEASFILETIME)
383         GetSystemTimeAsFileTime(&currTime);
384 #elif defined(HAVE_CLOCK_GETTIME)
385
386 # if defined(_POSIX_MONOTONIC_CLOCK)
387         clock_res = clock_gettime(CLOCK_MONOTONIC, &currTime);
388 # else
389         clock_res = clock_gettime(CLOCK_REALTIME, &currTime);
390 # endif
391         if (0 != clock_res)
392         {
393             return OC_STACK_TIMEOUT;
394         }
395 #else
396         ERROR Need PMTimeout implementation
397 #endif
398
399 #if defined(HAVE_GETSYSTEMTIMEASFILETIME)
400 #define HNS_TO_S(VAL)  ((VAL)/(10*1000*1000))
401         ULARGE_INTEGER currTimeInt;
402         ULARGE_INTEGER startTimeInt;
403
404         currTimeInt.LowPart  = currTime.dwLowDateTime;
405         currTimeInt.HighPart = currTime.dwHighDateTime;
406
407         startTimeInt.LowPart  = startTime.dwLowDateTime;
408         startTimeInt.HighPart = startTime.dwHighDateTime;
409
410         long elapsed = (long)HNS_TO_S(currTimeInt.QuadPart - startTimeInt.QuadPart);
411 #elif defined(HAVE_CLOCK_GETTIME)
412         long elapsed = (currTime.tv_sec - startTime.tv_sec);
413 #else
414         ERROR Need PMTimeout implementation
415 #endif
416         if (elapsed > waittime)
417         {
418             return OC_STACK_OK;
419         }
420         if (waitForStackResponse)
421         {
422             res = OCProcess();
423         }
424     }
425     return res;
426 }
427
428 /**
429  * Extract secure port information from payload of discovery response.
430  *
431  * @param[in] jsonStr response payload of /oic/res discovery.
432  *
433  * @return Secure port
434  */
435 uint16_t GetSecurePortFromJSON(char* jsonStr)
436 {
437     // TODO: Modify error handling
438     if (NULL == jsonStr)
439     {
440         return 0;
441     }
442     cJSON *jsonProp = NULL;
443     cJSON *jsonP = NULL;
444     cJSON *jsonPort = NULL;
445
446     cJSON *jsonRoot = cJSON_Parse(jsonStr);
447     if(!jsonRoot)
448     {
449         // TODO: Add error log & return default secure port
450         return 0;
451     }
452
453     jsonProp = cJSON_GetObjectItem(jsonRoot, "prop");
454     if(!jsonProp)
455     {
456         // TODO: Add error log & return default secure port
457         return 0;
458     }
459
460     jsonP = cJSON_GetObjectItem(jsonProp, "p");
461     if(!jsonP)
462     {
463         // TODO: Add error log & return default secure port
464         return 0;
465     }
466
467     jsonPort = cJSON_GetObjectItem(jsonP, "port");
468     if(!jsonPort)
469     {
470         // TODO: Add error log & return default secure port
471         return 0;
472     }
473
474     return (uint16_t)jsonPort->valueint;
475 }
476
477 bool PMGenerateQuery(bool isSecure,
478                      const char* address, uint16_t port,
479                      OCConnectivityType connType,
480                      char* buffer, size_t bufferSize, const char* uri)
481 {
482     if(!address || !buffer || !uri)
483     {
484         OIC_LOG(ERROR, TAG, "PMGenerateQuery : Invalid parameters.");
485         return false;
486     }
487
488     int snRet = 0;
489     char* prefix = (isSecure == true) ? COAPS_PREFIX : COAP_PREFIX;
490
491     switch(connType & CT_MASK_ADAPTER)
492     {
493         case CT_ADAPTER_IP:
494             switch(connType & CT_MASK_FLAGS & ~CT_FLAG_SECURE)
495             {
496                 case CT_IP_USE_V4:
497                         snRet = snprintf(buffer, bufferSize, "%s%s:%d%s",
498                                          prefix, address, port, uri);
499                     break;
500                 case CT_IP_USE_V6:
501                         snRet = snprintf(buffer, bufferSize, "%s[%s]:%d%s",
502                                          prefix, address, port, uri);
503                     break;
504                 default:
505                     OIC_LOG(ERROR, TAG, "Unknown address format.");
506                     return false;
507             }
508             // snprintf return value check
509             if (snRet < 0)
510             {
511                 OIC_LOG_V(ERROR, TAG, "PMGenerateQuery : Error (snprintf) %d\n", snRet);
512                 return false;
513             }
514             else if ((size_t)snRet >= bufferSize)
515             {
516                 OIC_LOG_V(ERROR, TAG, "PMGenerateQuery : Truncated (snprintf) %d\n", snRet);
517                 return false;
518             }
519
520             break;
521         // TODO: We need to verify tinyDTLS in below cases
522         case CT_ADAPTER_GATT_BTLE:
523         case CT_ADAPTER_RFCOMM_BTEDR:
524             OIC_LOG(ERROR, TAG, "Not supported connectivity adapter.");
525             return false;
526             break;
527         default:
528             OIC_LOG(ERROR, TAG, "Unknown connectivity adapter.");
529             return false;
530     }
531
532     return true;
533 }
534
535 static OCStackApplicationResult SecurityVersionDiscoveryHandler(void *ctx, OCDoHandle UNUSED,
536                                 OCClientResponse *clientResponse)
537 {
538     if (ctx == NULL)
539     {
540         OIC_LOG(ERROR, TAG, "Lost List of device information");
541         return OC_STACK_KEEP_TRANSACTION;
542     }
543     (void)UNUSED;
544     if (clientResponse)
545     {
546         if  (NULL == clientResponse->payload)
547         {
548             OIC_LOG(INFO, TAG, "Skiping Null payload");
549             return OC_STACK_KEEP_TRANSACTION;
550         }
551         if (OC_STACK_OK != clientResponse->result)
552         {
553             OIC_LOG(INFO, TAG, "Error in response");
554             return OC_STACK_KEEP_TRANSACTION;
555         }
556         else
557         {
558             if (PAYLOAD_TYPE_SECURITY != clientResponse->payload->type)
559             {
560                 OIC_LOG(INFO, TAG, "Unknown payload type");
561                 return OC_STACK_KEEP_TRANSACTION;
562             }
563
564             OicSecVer_t *ptrVer = NULL;
565             uint8_t *payload = ((OCSecurityPayload*)clientResponse->payload)->securityData;
566             size_t size = ((OCSecurityPayload*)clientResponse->payload)->payloadSize;
567
568             OCStackResult res = CBORPayloadToVer(payload, size, &ptrVer);
569             if ((NULL == ptrVer) && (OC_STACK_OK != res))
570             {
571                 OIC_LOG(INFO, TAG, "Ignoring malformed CBOR");
572                 return OC_STACK_KEEP_TRANSACTION;
573             }
574             else
575             {
576                 OIC_LOG(DEBUG, TAG, "Successfully converted ver cbor to bin.");
577
578                 //If this is owend device discovery we have to filter out the responses.
579                 DiscoveryInfo* pDInfo = (DiscoveryInfo*)ctx;
580                 res = UpdateSecVersionOfDevice(pDInfo->ppDevicesList, clientResponse->devAddr.addr,
581                                                          clientResponse->devAddr.port, ptrVer->secv);
582                 if (OC_STACK_OK != res)
583                 {
584                     OIC_LOG(ERROR, TAG, "Error while getting security version.");
585                     DeleteVerBinData(ptrVer);
586                     return OC_STACK_KEEP_TRANSACTION;
587                 }
588
589                 OIC_LOG(INFO, TAG, "= Discovered security version =");
590                 OIC_LOG_V(DEBUG, TAG, "IP %s", clientResponse->devAddr.addr);
591                 OIC_LOG_V(DEBUG, TAG, "PORT %d", clientResponse->devAddr.port);
592                 OIC_LOG_V(DEBUG, TAG, "VERSION %s", ptrVer->secv);
593
594                 OIC_LOG(INFO, TAG, "Exiting SecVersionDiscoveryHandler.");
595                 DeleteVerBinData(ptrVer);
596             }
597         }
598     }
599     else
600     {
601         OIC_LOG(INFO, TAG, "Skiping Null response");
602         return OC_STACK_KEEP_TRANSACTION;
603     }
604
605     return  OC_STACK_DELETE_TRANSACTION;
606 }
607
608 static OCStackApplicationResult SecurePortDiscoveryHandler(void *ctx, OCDoHandle UNUSED,
609                                  OCClientResponse *clientResponse)
610 {
611     if (ctx == NULL)
612     {
613         OIC_LOG(ERROR, TAG, "Lost List of device information");
614         return OC_STACK_DELETE_TRANSACTION;
615     }
616     (void)UNUSED;
617     if (clientResponse)
618     {
619         if  (NULL == clientResponse->payload)
620         {
621             OIC_LOG(INFO, TAG, "Skiping Null payload");
622         }
623         else
624         {
625             if (PAYLOAD_TYPE_DISCOVERY != clientResponse->payload->type)
626             {
627                 OIC_LOG(INFO, TAG, "Wrong payload type");
628                 return OC_STACK_DELETE_TRANSACTION;
629             }
630
631             uint16_t securePort = 0;
632             OCResourcePayload* resPayload = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
633
634             // Use seure port of doxm for OTM and Provision.
635             while (resPayload)
636             {
637                 if (0 == strncmp(resPayload->uri, OIC_RSRC_DOXM_URI, sizeof(OIC_RSRC_DOXM_URI)))
638                 {
639                     OIC_LOG_V(INFO,TAG,"resPaylod->uri:%s",resPayload->uri);
640                     OIC_LOG(INFO, TAG, "Found doxm resource.");
641                     break;
642                 }
643                 else
644                 {
645                     resPayload = resPayload->next;
646                 }
647             }
648             if (NULL == resPayload)
649             {
650                 OIC_LOG(ERROR, TAG, "Can not find doxm resource.");
651                 return OC_STACK_DELETE_TRANSACTION;
652             }
653             if (resPayload && resPayload->secure)
654             {
655                 securePort = resPayload->port;
656             }
657             else
658             {
659                 OIC_LOG(INFO, TAG, "Can not find secure port information.");
660                 return OC_STACK_DELETE_TRANSACTION;
661             }
662
663             DiscoveryInfo* pDInfo = (DiscoveryInfo*)ctx;
664             OCStackResult res = UpdateSecurePortOfDevice(pDInfo->ppDevicesList,
665                                                          clientResponse->devAddr.addr,
666                                                          clientResponse->devAddr.port, securePort);
667             if (OC_STACK_OK != res)
668             {
669                 OIC_LOG(ERROR, TAG, "Error while getting secure port.");
670                 return OC_STACK_DELETE_TRANSACTION;
671             }
672
673             res = SecurityVersionDiscovery(pDInfo, clientResponse);
674             if(OC_STACK_OK != res)
675             {
676                 OIC_LOG(ERROR, TAG, "Failed to SecurityVersionDiscovery");
677                 return OC_STACK_DELETE_TRANSACTION;
678             }
679
680             OIC_LOG(INFO, TAG, "Exiting SecurePortDiscoveryHandler.");
681         }
682
683         return  OC_STACK_DELETE_TRANSACTION;
684     }
685     else
686     {
687         OIC_LOG(INFO, TAG, "Skiping Null response");
688     }
689
690     return  OC_STACK_DELETE_TRANSACTION;
691 }
692
693 static OCStackApplicationResult DeviceDiscoveryHandler(void *ctx, OCDoHandle UNUSED,
694                                 OCClientResponse *clientResponse)
695 {
696     if (ctx == NULL)
697     {
698         OIC_LOG(ERROR, TAG, "Lost List of device information");
699         return OC_STACK_KEEP_TRANSACTION;
700     }
701     (void)UNUSED;
702     if (clientResponse)
703     {
704         if  (NULL == clientResponse->payload)
705         {
706             OIC_LOG(INFO, TAG, "Skiping Null payload");
707             return OC_STACK_KEEP_TRANSACTION;
708         }
709         if (OC_STACK_OK != clientResponse->result)
710         {
711             OIC_LOG(INFO, TAG, "Error in response");
712             return OC_STACK_KEEP_TRANSACTION;
713         }
714         else
715         {
716             if (PAYLOAD_TYPE_SECURITY != clientResponse->payload->type)
717             {
718                 OIC_LOG(INFO, TAG, "Unknown payload type");
719                 return OC_STACK_KEEP_TRANSACTION;
720             }
721
722             OicSecDoxm_t *ptrDoxm = NULL;
723             uint8_t *payload = ((OCSecurityPayload*)clientResponse->payload)->securityData;
724             size_t size = ((OCSecurityPayload*)clientResponse->payload)->payloadSize;
725
726             OCStackResult res = CBORPayloadToDoxm(payload, size, &ptrDoxm);
727             if ((NULL == ptrDoxm) || (OC_STACK_OK != res))
728             {
729                 OIC_LOG(INFO, TAG, "Ignoring malformed CBOR");
730                 return OC_STACK_KEEP_TRANSACTION;
731             }
732             else
733             {
734                 OIC_LOG(DEBUG, TAG, "Successfully converted doxm cbor to bin.");
735
736                 //If this is owend device discovery we have to filter out the responses.
737                 DiscoveryInfo* pDInfo = (DiscoveryInfo*)ctx;
738                 OCProvisionDev_t **ppDevicesList = pDInfo->ppDevicesList;
739
740                 // Get my device ID from doxm resource
741                 OicUuid_t myId;
742                 memset(&myId, 0, sizeof(myId));
743                 OCStackResult res = GetDoxmDevOwnerId(&myId);
744                 if(OC_STACK_OK != res)
745                 {
746                     OIC_LOG(ERROR, TAG, "Error while getting my device ID.");
747                     DeleteDoxmBinData(ptrDoxm);
748                     return OC_STACK_KEEP_TRANSACTION;
749                 }
750
751                 // If this is owned discovery response but owner is not me then discard it.
752                 if( (pDInfo->isOwnedDiscovery) &&
753                     (0 != memcmp(&ptrDoxm->owner.id, &myId.id, sizeof(myId.id))) )
754                 {
755                     OIC_LOG(DEBUG, TAG, "Discovered device is not owend by me");
756                     DeleteDoxmBinData(ptrDoxm);
757                     return OC_STACK_KEEP_TRANSACTION;
758                 }
759
760                 res = AddDevice(ppDevicesList, clientResponse->devAddr.addr,
761                         clientResponse->devAddr.port,
762                         clientResponse->devAddr.adapter,
763                         clientResponse->connType, ptrDoxm);
764                 if (OC_STACK_OK != res)
765                 {
766                     OIC_LOG(ERROR, TAG, "Error while adding data to linkedlist.");
767                     DeleteDoxmBinData(ptrDoxm);
768                     return OC_STACK_KEEP_TRANSACTION;
769                 }
770
771                 res = SecurePortDiscovery(pDInfo, clientResponse);
772                 if(OC_STACK_OK != res)
773                 {
774                     OIC_LOG(ERROR, TAG, "Failed to SecurePortDiscovery");
775                     DeleteDoxmBinData(ptrDoxm);
776                     return OC_STACK_KEEP_TRANSACTION;
777                 }
778
779                 OIC_LOG(INFO, TAG, "Exiting ProvisionDiscoveryHandler.");
780             }
781
782             return  OC_STACK_KEEP_TRANSACTION;
783         }
784     }
785     else
786     {
787         OIC_LOG(INFO, TAG, "Skiping Null response");
788         return OC_STACK_KEEP_TRANSACTION;
789     }
790
791     return  OC_STACK_DELETE_TRANSACTION;
792 }
793
794 /**
795  * Discover owned/unowned devices in the same IP subnet. .
796  *
797  * @param[in] waittime      Timeout in seconds.
798  * @param[in] isOwned       bool flag for owned / unowned discovery
799  * @param[in] ppDevicesList        List of OCProvisionDev_t.
800  *
801  * @return OC_STACK_OK on success otherwise error.
802  */
803 OCStackResult PMDeviceDiscovery(unsigned short waittime, bool isOwned, OCProvisionDev_t **ppDevicesList)
804 {
805     OIC_LOG(DEBUG, TAG, "IN PMDeviceDiscovery");
806
807     if (NULL != *ppDevicesList)
808     {
809         OIC_LOG(ERROR, TAG, "List is not null can cause memory leak");
810         return OC_STACK_INVALID_PARAM;
811     }
812
813     const char DOXM_OWNED_FALSE_MULTICAST_QUERY[] = "/oic/sec/doxm?Owned=FALSE";
814     const char DOXM_OWNED_TRUE_MULTICAST_QUERY[] = "/oic/sec/doxm?Owned=TRUE";
815
816     DiscoveryInfo *pDInfo = OICCalloc(1, sizeof(DiscoveryInfo));
817     if(NULL == pDInfo)
818     {
819         OIC_LOG(ERROR, TAG, "PMDeviceDiscovery : Memory allocation failed.");
820         return OC_STACK_NO_MEMORY;
821     }
822
823     pDInfo->ppDevicesList = ppDevicesList;
824     pDInfo->isOwnedDiscovery = isOwned;
825
826     OCCallbackData cbData;
827     cbData.cb = &DeviceDiscoveryHandler;
828     cbData.context = (void *)pDInfo;
829     cbData.cd = NULL;
830     OCStackResult res = OC_STACK_ERROR;
831
832     const char* query = isOwned ? DOXM_OWNED_TRUE_MULTICAST_QUERY :
833                                   DOXM_OWNED_FALSE_MULTICAST_QUERY;
834
835     OCDoHandle handle = NULL;
836     res = OCDoResource(&handle, OC_REST_DISCOVER, query, 0, 0,
837                                      CT_DEFAULT, OC_HIGH_QOS, &cbData, NULL, 0);
838     if (res != OC_STACK_OK)
839     {
840         OIC_LOG(ERROR, TAG, "OCStack resource error");
841         OICFree(pDInfo);
842         return res;
843     }
844
845     //Waiting for each response.
846     res = PMTimeout(waittime, true);
847     if(OC_STACK_OK != res)
848     {
849         OIC_LOG(ERROR, TAG, "Failed to wait response for secure discovery.");
850         OICFree(pDInfo);
851         OCStackResult resCancel = OCCancel(handle, OC_HIGH_QOS, NULL, 0);
852         if(OC_STACK_OK !=  resCancel)
853         {
854             OIC_LOG(ERROR, TAG, "Failed to remove registered callback");
855         }
856         return res;
857     }
858     res = OCCancel(handle,OC_HIGH_QOS,NULL,0);
859     if (OC_STACK_OK != res)
860     {
861         OIC_LOG(ERROR, TAG, "Failed to remove registered callback");
862         OICFree(pDInfo);
863         return res;
864     }
865     OIC_LOG(DEBUG, TAG, "OUT PMDeviceDiscovery");
866     OICFree(pDInfo);
867     return res;
868 }
869
870 static OCStackResult SecurePortDiscovery(DiscoveryInfo* discoveryInfo,
871                                          const OCClientResponse *clientResponse)
872 {
873     OIC_LOG(DEBUG, TAG, "IN SecurePortDiscovery");
874
875     if(NULL == discoveryInfo || NULL == clientResponse)
876     {
877         return OC_STACK_INVALID_PARAM;
878     }
879     //Try to the unicast discovery to getting secure port
880     char query[MAX_URI_LENGTH+MAX_QUERY_LENGTH+1] = {0};
881     if(!PMGenerateQuery(false,
882                         clientResponse->devAddr.addr, clientResponse->devAddr.port,
883                         clientResponse->connType,
884                         query, sizeof(query), OC_RSRVD_WELL_KNOWN_URI))
885     {
886         OIC_LOG(ERROR, TAG, "SecurePortDiscovery : Failed to generate query");
887         return OC_STACK_ERROR;
888     }
889     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
890
891     OCCallbackData cbData;
892     cbData.cb = &SecurePortDiscoveryHandler;
893     cbData.context = (void*)discoveryInfo;
894     cbData.cd = NULL;
895     OCStackResult ret = OCDoResource(NULL, OC_REST_DISCOVER, query, 0, 0,
896             clientResponse->connType, OC_HIGH_QOS, &cbData, NULL, 0);
897     if(OC_STACK_OK != ret)
898     {
899         OIC_LOG(ERROR, TAG, "Failed to Secure Port Discovery");
900         return ret;
901     }
902     else
903     {
904         OIC_LOG_V(INFO, TAG, "OCDoResource with [%s] Success", query);
905     }
906
907     OIC_LOG(DEBUG, TAG, "OUT SecurePortDiscovery");
908
909     return ret;
910 }
911
912 static OCStackResult SecurityVersionDiscovery(DiscoveryInfo* discoveryInfo,
913                                               const OCClientResponse *clientResponse)
914 {
915     OIC_LOG(DEBUG, TAG, "IN SecurityVersionDiscovery");
916
917     if(NULL == discoveryInfo || NULL == clientResponse)
918     {
919         return OC_STACK_INVALID_PARAM;
920     }
921
922     //Try to the unicast discovery to getting security version
923     char query[MAX_URI_LENGTH+MAX_QUERY_LENGTH+1] = {0};
924     if(!PMGenerateQuery(false,
925                         clientResponse->devAddr.addr, clientResponse->devAddr.port,
926                         clientResponse->connType,
927                         query, sizeof(query), OIC_RSRC_VER_URI))
928     {
929         OIC_LOG(ERROR, TAG, "SecurityVersionDiscovery : Failed to generate query");
930         return OC_STACK_ERROR;
931     }
932     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
933
934     OCCallbackData cbData;
935     cbData.cb = &SecurityVersionDiscoveryHandler;
936     cbData.context = (void*)discoveryInfo;
937     cbData.cd = NULL;
938     OCStackResult ret = OCDoResource(NULL, OC_REST_DISCOVER, query, 0, 0,
939             clientResponse->connType, OC_HIGH_QOS, &cbData, NULL, 0);
940     if(OC_STACK_OK != ret)
941     {
942         OIC_LOG(ERROR, TAG, "Failed to Security Version Discovery");
943         return ret;
944     }
945     else
946     {
947         OIC_LOG_V(INFO, TAG, "OCDoResource with [%s] Success", query);
948     }
949
950     OIC_LOG(DEBUG, TAG, "OUT SecurityVersionDiscovery");
951
952     return ret;
953 }
954
955 /**
956  * Function to print OCProvisionDev_t for debug purpose.
957  *
958  * @param[in] pDev Pointer to OCProvisionDev_t. It's information will be printed by OIC_LOG_XX
959  *
960  */
961 void PMPrintOCProvisionDev(const OCProvisionDev_t* pDev)
962 {
963     if (pDev)
964     {
965         OIC_LOG(DEBUG, TAG, "+++++ OCProvisionDev_t Information +++++");
966         OIC_LOG_V(DEBUG, TAG, "IP %s", pDev->endpoint.addr);
967         OIC_LOG_V(DEBUG, TAG, "PORT %d", pDev->endpoint.port);
968         OIC_LOG_V(DEBUG, TAG, "S-PORT %d", pDev->securePort);
969         OIC_LOG(DEBUG, TAG, "++++++++++++++++++++++++++++++++++++++++");
970     }
971     else
972     {
973         OIC_LOG(DEBUG, TAG, "+++++ OCProvisionDev_t is NULL +++++");
974     }
975 }
976
977 bool PMDeleteFromUUIDList(OCUuidList_t *pUuidList, OicUuid_t *targetId)
978 {
979     if(pUuidList == NULL || targetId == NULL)
980     {
981         return false;
982     }
983     OCUuidList_t *tmp1 = NULL,*tmp2=NULL;
984     LL_FOREACH_SAFE(pUuidList, tmp1, tmp2)
985     {
986         if(0 == memcmp(tmp1->dev.id, targetId->id, sizeof(targetId->id)))
987         {
988             LL_DELETE(pUuidList, tmp1);
989             OICFree(tmp1);
990             return true;
991         }
992     }
993     return false;
994 }