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