7ce7bc8204ebfc4dfc16d063240dbf7a4f4229e7
[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
349     uint64_t startTime = OICGetCurrentTime(TIME_IN_MS);
350     while (OC_STACK_OK == res)
351     {
352         uint64_t currTime = OICGetCurrentTime(TIME_IN_MS);
353
354         long elapsed = (long)((currTime - startTime) / MS_PER_SEC);
355         if (elapsed > waittime)
356         {
357             return OC_STACK_OK;
358         }
359         if (waitForStackResponse)
360         {
361             res = OCProcess();
362         }
363     }
364     return res;
365 }
366
367 /**
368  * Extract secure port information from payload of discovery response.
369  *
370  * @param[in] jsonStr response payload of /oic/res discovery.
371  *
372  * @return Secure port
373  */
374 uint16_t GetSecurePortFromJSON(char* jsonStr)
375 {
376     // TODO: Modify error handling
377     if (NULL == jsonStr)
378     {
379         return 0;
380     }
381     cJSON *jsonProp = NULL;
382     cJSON *jsonP = NULL;
383     cJSON *jsonPort = NULL;
384
385     cJSON *jsonRoot = cJSON_Parse(jsonStr);
386     if(!jsonRoot)
387     {
388         // TODO: Add error log & return default secure port
389         return 0;
390     }
391
392     jsonProp = cJSON_GetObjectItem(jsonRoot, "prop");
393     if(!jsonProp)
394     {
395         // TODO: Add error log & return default secure port
396         return 0;
397     }
398
399     jsonP = cJSON_GetObjectItem(jsonProp, "p");
400     if(!jsonP)
401     {
402         // TODO: Add error log & return default secure port
403         return 0;
404     }
405
406     jsonPort = cJSON_GetObjectItem(jsonP, "port");
407     if(!jsonPort)
408     {
409         // TODO: Add error log & return default secure port
410         return 0;
411     }
412
413     return (uint16_t)jsonPort->valueint;
414 }
415
416 bool PMGenerateQuery(bool isSecure,
417                      const char* address, uint16_t port,
418                      OCConnectivityType connType,
419                      char* buffer, size_t bufferSize, const char* uri)
420 {
421     if(!address || !buffer || !uri)
422     {
423         OIC_LOG(ERROR, TAG, "PMGenerateQuery : Invalid parameters.");
424         return false;
425     }
426
427     int snRet = 0;
428     char* prefix = (isSecure == true) ? COAPS_PREFIX : COAP_PREFIX;
429
430     switch(connType & CT_MASK_ADAPTER)
431     {
432         case CT_ADAPTER_IP:
433             switch(connType & CT_MASK_FLAGS & ~CT_FLAG_SECURE)
434             {
435                 case CT_IP_USE_V4:
436                         snRet = snprintf(buffer, bufferSize, "%s%s:%d%s",
437                                          prefix, address, port, uri);
438                     break;
439                 case CT_IP_USE_V6:
440                         snRet = snprintf(buffer, bufferSize, "%s[%s]:%d%s",
441                                          prefix, address, port, uri);
442                     break;
443                 default:
444                     OIC_LOG(ERROR, TAG, "Unknown address format.");
445                     return false;
446             }
447             // snprintf return value check
448             if (snRet < 0)
449             {
450                 OIC_LOG_V(ERROR, TAG, "PMGenerateQuery : Error (snprintf) %d\n", snRet);
451                 return false;
452             }
453             else if ((size_t)snRet >= bufferSize)
454             {
455                 OIC_LOG_V(ERROR, TAG, "PMGenerateQuery : Truncated (snprintf) %d\n", snRet);
456                 return false;
457             }
458
459             break;
460         // TODO: We need to verify tinyDTLS in below cases
461         case CT_ADAPTER_GATT_BTLE:
462         case CT_ADAPTER_RFCOMM_BTEDR:
463             OIC_LOG(ERROR, TAG, "Not supported connectivity adapter.");
464             return false;
465             break;
466         default:
467             OIC_LOG(ERROR, TAG, "Unknown connectivity adapter.");
468             return false;
469     }
470
471     return true;
472 }
473
474 static OCStackApplicationResult SecurityVersionDiscoveryHandler(void *ctx, OCDoHandle UNUSED,
475                                 OCClientResponse *clientResponse)
476 {
477     if (ctx == NULL)
478     {
479         OIC_LOG(ERROR, TAG, "Lost List of device information");
480         return OC_STACK_KEEP_TRANSACTION;
481     }
482     (void)UNUSED;
483     if (clientResponse)
484     {
485         if  (NULL == clientResponse->payload)
486         {
487             OIC_LOG(INFO, TAG, "Skiping Null payload");
488             return OC_STACK_KEEP_TRANSACTION;
489         }
490         if (OC_STACK_OK != clientResponse->result)
491         {
492             OIC_LOG(INFO, TAG, "Error in response");
493             return OC_STACK_KEEP_TRANSACTION;
494         }
495         else
496         {
497             if (PAYLOAD_TYPE_SECURITY != clientResponse->payload->type)
498             {
499                 OIC_LOG(INFO, TAG, "Unknown payload type");
500                 return OC_STACK_KEEP_TRANSACTION;
501             }
502
503             OicSecVer_t *ptrVer = NULL;
504             uint8_t *payload = ((OCSecurityPayload*)clientResponse->payload)->securityData;
505             size_t size = ((OCSecurityPayload*)clientResponse->payload)->payloadSize;
506
507             OCStackResult res = CBORPayloadToVer(payload, size, &ptrVer);
508             if ((NULL == ptrVer) && (OC_STACK_OK != res))
509             {
510                 OIC_LOG(INFO, TAG, "Ignoring malformed CBOR");
511                 return OC_STACK_KEEP_TRANSACTION;
512             }
513             else
514             {
515                 OIC_LOG(DEBUG, TAG, "Successfully converted ver cbor to bin.");
516
517                 //If this is owend device discovery we have to filter out the responses.
518                 DiscoveryInfo* pDInfo = (DiscoveryInfo*)ctx;
519                 res = UpdateSecVersionOfDevice(pDInfo->ppDevicesList, clientResponse->devAddr.addr,
520                                                          clientResponse->devAddr.port, ptrVer->secv);
521                 if (OC_STACK_OK != res)
522                 {
523                     OIC_LOG(ERROR, TAG, "Error while getting security version.");
524                     DeleteVerBinData(ptrVer);
525                     return OC_STACK_KEEP_TRANSACTION;
526                 }
527
528                 OIC_LOG(INFO, TAG, "= Discovered security version =");
529                 OIC_LOG_V(DEBUG, TAG, "IP %s", clientResponse->devAddr.addr);
530                 OIC_LOG_V(DEBUG, TAG, "PORT %d", clientResponse->devAddr.port);
531                 OIC_LOG_V(DEBUG, TAG, "VERSION %s", ptrVer->secv);
532
533                 OIC_LOG(INFO, TAG, "Exiting SecVersionDiscoveryHandler.");
534                 DeleteVerBinData(ptrVer);
535             }
536         }
537     }
538     else
539     {
540         OIC_LOG(INFO, TAG, "Skiping Null response");
541         return OC_STACK_KEEP_TRANSACTION;
542     }
543
544     return  OC_STACK_DELETE_TRANSACTION;
545 }
546
547 static OCStackApplicationResult SecurePortDiscoveryHandler(void *ctx, OCDoHandle UNUSED,
548                                  OCClientResponse *clientResponse)
549 {
550     if (ctx == NULL)
551     {
552         OIC_LOG(ERROR, TAG, "Lost List of device information");
553         return OC_STACK_DELETE_TRANSACTION;
554     }
555     (void)UNUSED;
556     if (clientResponse)
557     {
558         if  (NULL == clientResponse->payload)
559         {
560             OIC_LOG(INFO, TAG, "Skiping Null payload");
561         }
562         else
563         {
564             if (PAYLOAD_TYPE_DISCOVERY != clientResponse->payload->type)
565             {
566                 OIC_LOG(INFO, TAG, "Wrong payload type");
567                 return OC_STACK_DELETE_TRANSACTION;
568             }
569
570             uint16_t securePort = 0;
571             OCResourcePayload* resPayload = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
572
573             // Use seure port of doxm for OTM and Provision.
574             while (resPayload)
575             {
576                 if (0 == strncmp(resPayload->uri, OIC_RSRC_DOXM_URI, strlen(OIC_RSRC_DOXM_URI)))
577                 {
578                     OIC_LOG_V(INFO,TAG,"resPaylod->uri:%s",resPayload->uri);
579                     OIC_LOG(INFO, TAG, "Found doxm resource.");
580                     break;
581                 }
582                 else
583                 {
584                     resPayload = resPayload->next;
585                 }
586             }
587             if (NULL == resPayload)
588             {
589                 OIC_LOG(ERROR, TAG, "Can not find doxm resource.");
590                 return OC_STACK_DELETE_TRANSACTION;
591             }
592             if (resPayload && resPayload->secure)
593             {
594                 securePort = resPayload->port;
595             }
596             else
597             {
598                 OIC_LOG(INFO, TAG, "Can not find secure port information.");
599                 return OC_STACK_DELETE_TRANSACTION;
600             }
601
602             DiscoveryInfo* pDInfo = (DiscoveryInfo*)ctx;
603             OCStackResult res = UpdateSecurePortOfDevice(pDInfo->ppDevicesList,
604                                                          clientResponse->devAddr.addr,
605                                                          clientResponse->devAddr.port, securePort);
606             if (OC_STACK_OK != res)
607             {
608                 OIC_LOG(ERROR, TAG, "Error while getting secure port.");
609                 return OC_STACK_DELETE_TRANSACTION;
610             }
611
612             res = SecurityVersionDiscovery(pDInfo, clientResponse);
613             if(OC_STACK_OK != res)
614             {
615                 OIC_LOG(ERROR, TAG, "Failed to SecurityVersionDiscovery");
616                 return OC_STACK_DELETE_TRANSACTION;
617             }
618
619             OIC_LOG(INFO, TAG, "Exiting SecurePortDiscoveryHandler.");
620         }
621
622         return  OC_STACK_DELETE_TRANSACTION;
623     }
624     else
625     {
626         OIC_LOG(INFO, TAG, "Skiping Null response");
627     }
628
629     return  OC_STACK_DELETE_TRANSACTION;
630 }
631
632 static OCStackApplicationResult DeviceDiscoveryHandler(void *ctx, OCDoHandle UNUSED,
633                                 OCClientResponse *clientResponse)
634 {
635     if (ctx == NULL)
636     {
637         OIC_LOG(ERROR, TAG, "Lost List of device information");
638         return OC_STACK_KEEP_TRANSACTION;
639     }
640     (void)UNUSED;
641     if (clientResponse)
642     {
643         if  (NULL == clientResponse->payload)
644         {
645             OIC_LOG(INFO, TAG, "Skiping Null payload");
646             return OC_STACK_KEEP_TRANSACTION;
647         }
648         if (OC_STACK_OK != clientResponse->result)
649         {
650             OIC_LOG(INFO, TAG, "Error in response");
651             return OC_STACK_KEEP_TRANSACTION;
652         }
653         else
654         {
655             if (PAYLOAD_TYPE_SECURITY != clientResponse->payload->type)
656             {
657                 OIC_LOG(INFO, TAG, "Unknown payload type");
658                 return OC_STACK_KEEP_TRANSACTION;
659             }
660
661             OicSecDoxm_t *ptrDoxm = NULL;
662             uint8_t *payload = ((OCSecurityPayload*)clientResponse->payload)->securityData;
663             size_t size = ((OCSecurityPayload*)clientResponse->payload)->payloadSize;
664
665             OCStackResult res = CBORPayloadToDoxm(payload, size, &ptrDoxm);
666             if ((NULL == ptrDoxm) || (OC_STACK_OK != res))
667             {
668                 OIC_LOG(INFO, TAG, "Ignoring malformed CBOR");
669                 return OC_STACK_KEEP_TRANSACTION;
670             }
671             else
672             {
673                 OIC_LOG(DEBUG, TAG, "Successfully converted doxm cbor to bin.");
674
675                 //If this is owend device discovery we have to filter out the responses.
676                 DiscoveryInfo* pDInfo = (DiscoveryInfo*)ctx;
677                 OCProvisionDev_t **ppDevicesList = pDInfo->ppDevicesList;
678
679                 // Get my device ID from doxm resource
680                 OicUuid_t myId;
681                 memset(&myId, 0, sizeof(myId));
682                 OCStackResult res = GetDoxmDevOwnerId(&myId);
683                 if(OC_STACK_OK != res)
684                 {
685                     OIC_LOG(ERROR, TAG, "Error while getting my device ID.");
686                     DeleteDoxmBinData(ptrDoxm);
687                     return OC_STACK_KEEP_TRANSACTION;
688                 }
689
690                 // If this is owned discovery response but owner is not me then discard it.
691                 if( (pDInfo->isOwnedDiscovery) &&
692                     (0 != memcmp(&ptrDoxm->owner.id, &myId.id, sizeof(myId.id))) )
693                 {
694                     OIC_LOG(DEBUG, TAG, "Discovered device is not owend by me");
695                     DeleteDoxmBinData(ptrDoxm);
696                     return OC_STACK_KEEP_TRANSACTION;
697                 }
698
699                 res = GetDoxmDeviceID(&myId);
700                 if(OC_STACK_OK != res)
701                 {
702                     OIC_LOG(ERROR, TAG, "Error while getting my UUID.");
703                     DeleteDoxmBinData(ptrDoxm);
704                     return OC_STACK_KEEP_TRANSACTION;
705                 }
706                 //if this is owned discovery and this is PT's reply, discard it
707                 if((pDInfo->isOwnedDiscovery) &&
708                         (0 == memcmp(&ptrDoxm->deviceID.id, &myId.id, sizeof(myId.id))) )
709                 {
710                     OIC_LOG(DEBUG, TAG, "discarding provision tool's reply");
711                     DeleteDoxmBinData(ptrDoxm);
712                     return OC_STACK_KEEP_TRANSACTION;
713                 }
714
715                 res = AddDevice(ppDevicesList, clientResponse->devAddr.addr,
716                         clientResponse->devAddr.port,
717                         clientResponse->devAddr.adapter,
718                         clientResponse->connType, ptrDoxm);
719                 if (OC_STACK_OK != res)
720                 {
721                     OIC_LOG(ERROR, TAG, "Error while adding data to linkedlist.");
722                     DeleteDoxmBinData(ptrDoxm);
723                     return OC_STACK_KEEP_TRANSACTION;
724                 }
725
726                 res = SecurePortDiscovery(pDInfo, clientResponse);
727                 if(OC_STACK_OK != res)
728                 {
729                     OIC_LOG(ERROR, TAG, "Failed to SecurePortDiscovery");
730                     DeleteDoxmBinData(ptrDoxm);
731                     return OC_STACK_KEEP_TRANSACTION;
732                 }
733
734                 OIC_LOG(INFO, TAG, "Exiting ProvisionDiscoveryHandler.");
735             }
736
737             return  OC_STACK_KEEP_TRANSACTION;
738         }
739     }
740     else
741     {
742         OIC_LOG(INFO, TAG, "Skiping Null response");
743         return OC_STACK_KEEP_TRANSACTION;
744     }
745
746     return  OC_STACK_DELETE_TRANSACTION;
747 }
748
749 /**
750  * Discover owned/unowned devices in the same IP subnet. .
751  *
752  * @param[in] waittime      Timeout in seconds.
753  * @param[in] isOwned       bool flag for owned / unowned discovery
754  * @param[in] ppDevicesList        List of OCProvisionDev_t.
755  *
756  * @return OC_STACK_OK on success otherwise error.
757  */
758 OCStackResult PMDeviceDiscovery(unsigned short waittime, bool isOwned, OCProvisionDev_t **ppDevicesList)
759 {
760     OIC_LOG(DEBUG, TAG, "IN PMDeviceDiscovery");
761
762     if (NULL != *ppDevicesList)
763     {
764         OIC_LOG(ERROR, TAG, "List is not null can cause memory leak");
765         return OC_STACK_INVALID_PARAM;
766     }
767
768     const char DOXM_OWNED_FALSE_MULTICAST_QUERY[] = "/oic/sec/doxm?Owned=FALSE";
769     const char DOXM_OWNED_TRUE_MULTICAST_QUERY[] = "/oic/sec/doxm?Owned=TRUE";
770
771     DiscoveryInfo *pDInfo = OICCalloc(1, sizeof(DiscoveryInfo));
772     if(NULL == pDInfo)
773     {
774         OIC_LOG(ERROR, TAG, "PMDeviceDiscovery : Memory allocation failed.");
775         return OC_STACK_NO_MEMORY;
776     }
777
778     pDInfo->ppDevicesList = ppDevicesList;
779     pDInfo->isOwnedDiscovery = isOwned;
780
781     OCCallbackData cbData;
782     cbData.cb = &DeviceDiscoveryHandler;
783     cbData.context = (void *)pDInfo;
784     cbData.cd = NULL;
785     OCStackResult res = OC_STACK_ERROR;
786
787     const char* query = isOwned ? DOXM_OWNED_TRUE_MULTICAST_QUERY :
788                                   DOXM_OWNED_FALSE_MULTICAST_QUERY;
789
790     OCDoHandle handle = NULL;
791     res = OCDoResource(&handle, OC_REST_DISCOVER, query, 0, 0,
792                                      CT_DEFAULT, OC_HIGH_QOS, &cbData, NULL, 0);
793     if (res != OC_STACK_OK)
794     {
795         OIC_LOG(ERROR, TAG, "OCStack resource error");
796         OICFree(pDInfo);
797         return res;
798     }
799
800     //Waiting for each response.
801     res = PMTimeout(waittime, true);
802     if(OC_STACK_OK != res)
803     {
804         OIC_LOG(ERROR, TAG, "Failed to wait response for secure discovery.");
805         OICFree(pDInfo);
806         OCStackResult resCancel = OCCancel(handle, OC_HIGH_QOS, NULL, 0);
807         if(OC_STACK_OK !=  resCancel)
808         {
809             OIC_LOG(ERROR, TAG, "Failed to remove registered callback");
810         }
811         return res;
812     }
813     res = OCCancel(handle,OC_HIGH_QOS,NULL,0);
814     if (OC_STACK_OK != res)
815     {
816         OIC_LOG(ERROR, TAG, "Failed to remove registered callback");
817         OICFree(pDInfo);
818         return res;
819     }
820     OIC_LOG(DEBUG, TAG, "OUT PMDeviceDiscovery");
821     OICFree(pDInfo);
822     return res;
823 }
824
825 static OCStackResult SecurePortDiscovery(DiscoveryInfo* discoveryInfo,
826                                          const OCClientResponse *clientResponse)
827 {
828     OIC_LOG(DEBUG, TAG, "IN SecurePortDiscovery");
829
830     if(NULL == discoveryInfo || NULL == clientResponse)
831     {
832         return OC_STACK_INVALID_PARAM;
833     }
834     //Try to the unicast discovery to getting secure port
835     char query[MAX_URI_LENGTH+MAX_QUERY_LENGTH+1] = {0};
836     if(!PMGenerateQuery(false,
837                         clientResponse->devAddr.addr, clientResponse->devAddr.port,
838                         clientResponse->connType,
839                         query, sizeof(query), OC_RSRVD_WELL_KNOWN_URI))
840     {
841         OIC_LOG(ERROR, TAG, "SecurePortDiscovery : Failed to generate query");
842         return OC_STACK_ERROR;
843     }
844     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
845
846     OCCallbackData cbData;
847     cbData.cb = &SecurePortDiscoveryHandler;
848     cbData.context = (void*)discoveryInfo;
849     cbData.cd = NULL;
850     OCStackResult ret = OCDoResource(NULL, OC_REST_DISCOVER, query, 0, 0,
851             clientResponse->connType, OC_HIGH_QOS, &cbData, NULL, 0);
852     if(OC_STACK_OK != ret)
853     {
854         OIC_LOG(ERROR, TAG, "Failed to Secure Port Discovery");
855         return ret;
856     }
857     else
858     {
859         OIC_LOG_V(INFO, TAG, "OCDoResource with [%s] Success", query);
860     }
861
862     OIC_LOG(DEBUG, TAG, "OUT SecurePortDiscovery");
863
864     return ret;
865 }
866
867 static OCStackResult SecurityVersionDiscovery(DiscoveryInfo* discoveryInfo,
868                                               const OCClientResponse *clientResponse)
869 {
870     OIC_LOG(DEBUG, TAG, "IN SecurityVersionDiscovery");
871
872     if(NULL == discoveryInfo || NULL == clientResponse)
873     {
874         return OC_STACK_INVALID_PARAM;
875     }
876
877     //Try to the unicast discovery to getting security version
878     char query[MAX_URI_LENGTH+MAX_QUERY_LENGTH+1] = {0};
879     if(!PMGenerateQuery(false,
880                         clientResponse->devAddr.addr, clientResponse->devAddr.port,
881                         clientResponse->connType,
882                         query, sizeof(query), OIC_RSRC_VER_URI))
883     {
884         OIC_LOG(ERROR, TAG, "SecurityVersionDiscovery : Failed to generate query");
885         return OC_STACK_ERROR;
886     }
887     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
888
889     OCCallbackData cbData;
890     cbData.cb = &SecurityVersionDiscoveryHandler;
891     cbData.context = (void*)discoveryInfo;
892     cbData.cd = NULL;
893     OCStackResult ret = OCDoResource(NULL, OC_REST_DISCOVER, query, 0, 0,
894             clientResponse->connType, OC_HIGH_QOS, &cbData, NULL, 0);
895     if(OC_STACK_OK != ret)
896     {
897         OIC_LOG(ERROR, TAG, "Failed to Security Version Discovery");
898         return ret;
899     }
900     else
901     {
902         OIC_LOG_V(INFO, TAG, "OCDoResource with [%s] Success", query);
903     }
904
905     OIC_LOG(DEBUG, TAG, "OUT SecurityVersionDiscovery");
906
907     return ret;
908 }
909
910 /**
911  * Function to print OCProvisionDev_t for debug purpose.
912  *
913  * @param[in] pDev Pointer to OCProvisionDev_t. It's information will be printed by OIC_LOG_XX
914  *
915  */
916 void PMPrintOCProvisionDev(const OCProvisionDev_t* pDev)
917 {
918     if (pDev)
919     {
920         OIC_LOG(DEBUG, TAG, "+++++ OCProvisionDev_t Information +++++");
921         OIC_LOG_V(DEBUG, TAG, "IP %s", pDev->endpoint.addr);
922         OIC_LOG_V(DEBUG, TAG, "PORT %d", pDev->endpoint.port);
923         OIC_LOG_V(DEBUG, TAG, "S-PORT %d", pDev->securePort);
924         OIC_LOG(DEBUG, TAG, "++++++++++++++++++++++++++++++++++++++++");
925     }
926     else
927     {
928         OIC_LOG(DEBUG, TAG, "+++++ OCProvisionDev_t is NULL +++++");
929     }
930 }
931
932 bool PMDeleteFromUUIDList(OCUuidList_t **pUuidList, OicUuid_t *targetId)
933 {
934     if(*pUuidList == NULL || targetId == NULL)
935     {
936         return false;
937     }
938     OCUuidList_t *tmp1 = NULL,*tmp2=NULL;
939     LL_FOREACH_SAFE(*pUuidList, tmp1, tmp2)
940     {
941         if(0 == memcmp(tmp1->dev.id, targetId->id, sizeof(targetId->id)))
942         {
943             LL_DELETE(*pUuidList, tmp1);
944             OICFree(tmp1);
945             return true;
946         }
947     }
948     return false;
949 }