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