(double free) crash occurred when discovering device
[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             // Use seure port of doxm for OTM and Provision.
588             while (resPayload)
589             {
590                 if (0 == strncmp(resPayload->uri, OIC_RSRC_DOXM_URI, strlen(OIC_RSRC_DOXM_URI)))
591                 {
592                     OIC_LOG_V(INFO,TAG,"resPaylod->uri:%s",resPayload->uri);
593                     OIC_LOG(INFO, TAG, "Found doxm resource.");
594                     break;
595                 }
596                 else
597                 {
598                     resPayload = resPayload->next;
599                 }
600             }
601             if (NULL == resPayload)
602             {
603                 OIC_LOG(ERROR, TAG, "Can not find doxm resource.");
604                 return OC_STACK_DELETE_TRANSACTION;
605             }
606             if (resPayload && resPayload->secure)
607             {
608                 securePort = resPayload->port;
609             }
610             else
611             {
612                 OIC_LOG(INFO, TAG, "Can not find secure port information.");
613                 return OC_STACK_DELETE_TRANSACTION;
614             }
615
616             DiscoveryInfo* pDInfo = (DiscoveryInfo*)ctx;
617             OCStackResult res = UpdateSecurePortOfDevice(pDInfo->ppDevicesList,
618                                                          clientResponse->devAddr.addr,
619                                                          clientResponse->devAddr.port, securePort);
620             if (OC_STACK_OK != res)
621             {
622                 OIC_LOG(ERROR, TAG, "Error while getting secure port.");
623                 return OC_STACK_DELETE_TRANSACTION;
624             }
625
626             res = SecurityVersionDiscovery(pDInfo, clientResponse);
627             if(OC_STACK_OK != res)
628             {
629                 OIC_LOG(ERROR, TAG, "Failed to SecurityVersionDiscovery");
630                 return OC_STACK_DELETE_TRANSACTION;
631             }
632
633             OIC_LOG(INFO, TAG, "Exiting SecurePortDiscoveryHandler.");
634         }
635
636         return  OC_STACK_DELETE_TRANSACTION;
637     }
638     else
639     {
640         OIC_LOG(INFO, TAG, "Skiping Null response");
641     }
642
643     return  OC_STACK_DELETE_TRANSACTION;
644 }
645
646 static OCStackApplicationResult DeviceDiscoveryHandler(void *ctx, OCDoHandle UNUSED,
647                                 OCClientResponse *clientResponse)
648 {
649     if (ctx == NULL)
650     {
651         OIC_LOG(ERROR, TAG, "Lost List of device information");
652         return OC_STACK_KEEP_TRANSACTION;
653     }
654     (void)UNUSED;
655     if (clientResponse)
656     {
657         if  (NULL == clientResponse->payload)
658         {
659             OIC_LOG(INFO, TAG, "Skiping Null payload");
660             return OC_STACK_KEEP_TRANSACTION;
661         }
662         if (OC_STACK_OK != clientResponse->result)
663         {
664             OIC_LOG(INFO, TAG, "Error in response");
665             return OC_STACK_KEEP_TRANSACTION;
666         }
667         else
668         {
669             if (PAYLOAD_TYPE_SECURITY != clientResponse->payload->type)
670             {
671                 OIC_LOG(INFO, TAG, "Unknown payload type");
672                 return OC_STACK_KEEP_TRANSACTION;
673             }
674
675             OicSecDoxm_t *ptrDoxm = NULL;
676             uint8_t *payload = ((OCSecurityPayload*)clientResponse->payload)->securityData;
677             size_t size = ((OCSecurityPayload*)clientResponse->payload)->payloadSize;
678
679             OCStackResult res = CBORPayloadToDoxm(payload, size, &ptrDoxm);
680             if ((NULL == ptrDoxm) || (OC_STACK_OK != res))
681             {
682                 OIC_LOG(INFO, TAG, "Ignoring malformed CBOR");
683                 return OC_STACK_KEEP_TRANSACTION;
684             }
685             else
686             {
687                 OIC_LOG(DEBUG, TAG, "Successfully converted doxm cbor to bin.");
688
689                 //If this is owend device discovery we have to filter out the responses.
690                 DiscoveryInfo* pDInfo = (DiscoveryInfo*)ctx;
691                 OCProvisionDev_t **ppDevicesList = pDInfo->ppDevicesList;
692
693                 // Get my device ID from doxm resource
694                 OicUuid_t myId;
695                 memset(&myId, 0, sizeof(myId));
696                 OCStackResult res = GetDoxmDevOwnerId(&myId);
697                 if(OC_STACK_OK != res)
698                 {
699                     OIC_LOG(ERROR, TAG, "Error while getting my device ID.");
700                     DeleteDoxmBinData(ptrDoxm);
701                     return OC_STACK_KEEP_TRANSACTION;
702                 }
703
704                 // If this is owned discovery response but owner is not me then discard it.
705                 if( (pDInfo->isOwnedDiscovery) &&
706                     (0 != memcmp(&ptrDoxm->owner.id, &myId.id, sizeof(myId.id))) )
707                 {
708                     OIC_LOG(DEBUG, TAG, "Discovered device is not owend by me");
709                     DeleteDoxmBinData(ptrDoxm);
710                     return OC_STACK_KEEP_TRANSACTION;
711                 }
712
713                 res = GetDoxmDeviceID(&myId);
714                 if(OC_STACK_OK != res)
715                 {
716                     OIC_LOG(ERROR, TAG, "Error while getting my UUID.");
717                     DeleteDoxmBinData(ptrDoxm);
718                     return OC_STACK_KEEP_TRANSACTION;
719                 }
720                 //if this is owned discovery and this is PT's reply, discard it
721                 if((pDInfo->isOwnedDiscovery) &&
722                         (0 == memcmp(&ptrDoxm->deviceID.id, &myId.id, sizeof(myId.id))) )
723                 {
724                     OIC_LOG(DEBUG, TAG, "discarding provision tool's reply");
725                     DeleteDoxmBinData(ptrDoxm);
726                     return OC_STACK_KEEP_TRANSACTION;
727                 }
728
729                 res = AddDevice(ppDevicesList, clientResponse->devAddr.addr,
730                         clientResponse->devAddr.port,
731                         clientResponse->devAddr.adapter,
732                         clientResponse->connType, ptrDoxm);
733                 if (OC_STACK_OK != res)
734                 {
735                     OIC_LOG(ERROR, TAG, "Error while adding data to linkedlist.");
736                     DeleteDoxmBinData(ptrDoxm);
737                     return OC_STACK_KEEP_TRANSACTION;
738                 }
739
740                 res = SecurePortDiscovery(pDInfo, clientResponse);
741                 if(OC_STACK_OK != res)
742                 {
743                     OIC_LOG(ERROR, TAG, "Failed to SecurePortDiscovery");
744                     DeleteDoxmBinData(ptrDoxm);
745                     return OC_STACK_KEEP_TRANSACTION;
746                 }
747
748                 OIC_LOG(INFO, TAG, "Exiting ProvisionDiscoveryHandler.");
749             }
750
751             return  OC_STACK_KEEP_TRANSACTION;
752         }
753     }
754     else
755     {
756         OIC_LOG(INFO, TAG, "Skiping Null response");
757         return OC_STACK_KEEP_TRANSACTION;
758     }
759
760     return  OC_STACK_DELETE_TRANSACTION;
761 }
762
763 /**
764  * Discover owned/unowned devices in the same IP subnet. .
765  *
766  * @param[in] waittime      Timeout in seconds.
767  * @param[in] isOwned       bool flag for owned / unowned discovery
768  * @param[in] ppDevicesList        List of OCProvisionDev_t.
769  *
770  * @return OC_STACK_OK on success otherwise error.
771  */
772 OCStackResult PMDeviceDiscovery(unsigned short waittime, bool isOwned, OCProvisionDev_t **ppDevicesList)
773 {
774     OIC_LOG(DEBUG, TAG, "IN PMDeviceDiscovery");
775
776     if (NULL != *ppDevicesList)
777     {
778         OIC_LOG(ERROR, TAG, "List is not null can cause memory leak");
779         return OC_STACK_INVALID_PARAM;
780     }
781
782     const char DOXM_OWNED_FALSE_MULTICAST_QUERY[] = "/oic/sec/doxm?Owned=FALSE";
783     const char DOXM_OWNED_TRUE_MULTICAST_QUERY[] = "/oic/sec/doxm?Owned=TRUE";
784
785     DiscoveryInfo *pDInfo = OICCalloc(1, sizeof(DiscoveryInfo));
786     if(NULL == pDInfo)
787     {
788         OIC_LOG(ERROR, TAG, "PMDeviceDiscovery : Memory allocation failed.");
789         return OC_STACK_NO_MEMORY;
790     }
791
792     pDInfo->ppDevicesList = ppDevicesList;
793     pDInfo->isOwnedDiscovery = isOwned;
794
795     OCCallbackData cbData;
796     cbData.cb = &DeviceDiscoveryHandler;
797     cbData.context = (void *)pDInfo;
798     cbData.cd = NULL;
799     OCStackResult res = OC_STACK_ERROR;
800
801     const char* query = isOwned ? DOXM_OWNED_TRUE_MULTICAST_QUERY :
802                                   DOXM_OWNED_FALSE_MULTICAST_QUERY;
803
804     OCDoHandle handle = NULL;
805     res = OCDoResource(&handle, OC_REST_DISCOVER, query, 0, 0,
806                                      CT_DEFAULT, OC_HIGH_QOS, &cbData, NULL, 0);
807     if (res != OC_STACK_OK)
808     {
809         OIC_LOG(ERROR, TAG, "OCStack resource error");
810         OICFree(pDInfo);
811         return res;
812     }
813
814     //Waiting for each response.
815     res = PMTimeout(waittime, true);
816     if(OC_STACK_OK != res)
817     {
818         OIC_LOG(ERROR, TAG, "Failed to wait response for secure discovery.");
819         OICFree(pDInfo);
820         OCStackResult resCancel = OCCancel(handle, OC_HIGH_QOS, NULL, 0);
821         if(OC_STACK_OK !=  resCancel)
822         {
823             OIC_LOG(ERROR, TAG, "Failed to remove registered callback");
824         }
825         return res;
826     }
827     res = OCCancel(handle,OC_HIGH_QOS,NULL,0);
828     if (OC_STACK_OK != res)
829     {
830         OIC_LOG(ERROR, TAG, "Failed to remove registered callback");
831         OICFree(pDInfo);
832         return res;
833     }
834     OIC_LOG(DEBUG, TAG, "OUT PMDeviceDiscovery");
835     OICFree(pDInfo);
836     return res;
837 }
838
839 static OCStackResult SecurePortDiscovery(DiscoveryInfo* discoveryInfo,
840                                          const OCClientResponse *clientResponse)
841 {
842     OIC_LOG(DEBUG, TAG, "IN SecurePortDiscovery");
843
844     if(NULL == discoveryInfo || NULL == clientResponse)
845     {
846         return OC_STACK_INVALID_PARAM;
847     }
848     //Try to the unicast discovery to getting secure port
849     char query[MAX_URI_LENGTH+MAX_QUERY_LENGTH+1] = {0};
850     if(!PMGenerateQuery(false,
851                         clientResponse->devAddr.addr, clientResponse->devAddr.port,
852                         clientResponse->connType,
853                         query, sizeof(query), OC_RSRVD_WELL_KNOWN_URI))
854     {
855         OIC_LOG(ERROR, TAG, "SecurePortDiscovery : Failed to generate query");
856         return OC_STACK_ERROR;
857     }
858     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
859
860     OCCallbackData cbData;
861     cbData.cb = &SecurePortDiscoveryHandler;
862     cbData.context = (void*)discoveryInfo;
863     cbData.cd = NULL;
864     OCStackResult ret = OCDoResource(NULL, OC_REST_DISCOVER, query, 0, 0,
865             clientResponse->connType, OC_HIGH_QOS, &cbData, NULL, 0);
866     if(OC_STACK_OK != ret)
867     {
868         OIC_LOG(ERROR, TAG, "Failed to Secure Port Discovery");
869         return ret;
870     }
871     else
872     {
873         OIC_LOG_V(INFO, TAG, "OCDoResource with [%s] Success", query);
874     }
875
876     OIC_LOG(DEBUG, TAG, "OUT SecurePortDiscovery");
877
878     return ret;
879 }
880
881 static OCStackResult SecurityVersionDiscovery(DiscoveryInfo* discoveryInfo,
882                                               const OCClientResponse *clientResponse)
883 {
884     OIC_LOG(DEBUG, TAG, "IN SecurityVersionDiscovery");
885
886     if(NULL == discoveryInfo || NULL == clientResponse)
887     {
888         return OC_STACK_INVALID_PARAM;
889     }
890
891     //Try to the unicast discovery to getting security version
892     char query[MAX_URI_LENGTH+MAX_QUERY_LENGTH+1] = {0};
893     if(!PMGenerateQuery(false,
894                         clientResponse->devAddr.addr, clientResponse->devAddr.port,
895                         clientResponse->connType,
896                         query, sizeof(query), OIC_RSRC_VER_URI))
897     {
898         OIC_LOG(ERROR, TAG, "SecurityVersionDiscovery : Failed to generate query");
899         return OC_STACK_ERROR;
900     }
901     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
902
903     OCCallbackData cbData;
904     cbData.cb = &SecurityVersionDiscoveryHandler;
905     cbData.context = (void*)discoveryInfo;
906     cbData.cd = NULL;
907     OCStackResult ret = OCDoResource(NULL, OC_REST_DISCOVER, query, 0, 0,
908             clientResponse->connType, OC_HIGH_QOS, &cbData, NULL, 0);
909     if(OC_STACK_OK != ret)
910     {
911         OIC_LOG(ERROR, TAG, "Failed to Security Version Discovery");
912         return ret;
913     }
914     else
915     {
916         OIC_LOG_V(INFO, TAG, "OCDoResource with [%s] Success", query);
917     }
918
919     OIC_LOG(DEBUG, TAG, "OUT SecurityVersionDiscovery");
920
921     return ret;
922 }
923
924 /**
925  * Function to print OCProvisionDev_t for debug purpose.
926  *
927  * @param[in] pDev Pointer to OCProvisionDev_t. It's information will be printed by OIC_LOG_XX
928  *
929  */
930 void PMPrintOCProvisionDev(const OCProvisionDev_t* pDev)
931 {
932     if (pDev)
933     {
934         OIC_LOG(DEBUG, TAG, "+++++ OCProvisionDev_t Information +++++");
935         OIC_LOG_V(DEBUG, TAG, "IP %s", pDev->endpoint.addr);
936         OIC_LOG_V(DEBUG, TAG, "PORT %d", pDev->endpoint.port);
937         OIC_LOG_V(DEBUG, TAG, "S-PORT %d", pDev->securePort);
938         OIC_LOG(DEBUG, TAG, "++++++++++++++++++++++++++++++++++++++++");
939     }
940     else
941     {
942         OIC_LOG(DEBUG, TAG, "+++++ OCProvisionDev_t is NULL +++++");
943     }
944 }
945
946 bool PMDeleteFromUUIDList(OCUuidList_t **pUuidList, OicUuid_t *targetId)
947 {
948     if(*pUuidList == NULL || targetId == NULL)
949     {
950         return false;
951     }
952     OCUuidList_t *tmp1 = NULL,*tmp2=NULL;
953     LL_FOREACH_SAFE(*pUuidList, tmp1, tmp2)
954     {
955         if(0 == memcmp(tmp1->dev.id, targetId->id, sizeof(targetId->id)))
956         {
957             LL_DELETE(*pUuidList, tmp1);
958             OICFree(tmp1);
959             return true;
960         }
961     }
962     return false;
963 }