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