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