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