Merge branch 'master' into simulator
[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 <unistd.h>
25 #include <string.h>
26 #include <time.h>
27 #include <sys/time.h>
28
29 #include "ocstack.h"
30 #include "oic_malloc.h"
31 #include "oic_string.h"
32 #include "logger.h"
33 #include "cJSON.h"
34 #include "utlist.h"
35 #include "ocpayload.h"
36
37 #include "securevirtualresourcetypes.h"
38 #include "srmresourcestrings.h" //@note: SRM's internal header
39 #include "doxmresource.h"       //@note: SRM's internal header
40 #include "pstatresource.h"      //@note: SRM's internal header
41
42 #include "pmtypes.h"
43 #include "pmutility.h"
44
45 #define TAG ("PM-UTILITY")
46
47 /**
48  * Function to search node in linked list that matches given IP and port.
49  *
50  * @param[in] pList         List of OCProvisionDev_t.
51  * @param[in] addr          address of target device.
52  * @param[in] port          port of remote server.
53  *
54  * @return pointer of OCProvisionDev_t if exist, otherwise NULL
55  */
56 OCProvisionDev_t* GetDevice(OCProvisionDev_t **ppDevicesList, const char* addr, const uint16_t port)
57 {
58     if(NULL == addr || NULL == *ppDevicesList)
59     {
60         OC_LOG_V(ERROR, TAG, "Invalid Input parameters in [%s]\n", __FUNCTION__);
61         return NULL;
62     }
63
64     OCProvisionDev_t *ptr = NULL;
65     LL_FOREACH(*ppDevicesList, ptr)
66     {
67         if( strcmp(ptr->endpoint.addr, addr) == 0 && port == ptr->endpoint.port)
68         {
69             return ptr;
70         }
71     }
72
73     return NULL;
74 }
75
76
77 /**
78  * Add device information to list.
79  *
80  * @param[in] pList         List of OCProvisionDev_t.
81  * @param[in] addr          address of target device.
82  * @param[in] port          port of remote server.
83  * @param[in] adapter       adapter type of endpoint.
84  * @param[in] doxm          pointer to doxm instance.
85  * @param[in] connType  connectivity type of endpoint
86  *
87  * @return OC_STACK_OK for success and errorcode otherwise.
88  */
89 OCStackResult AddDevice(OCProvisionDev_t **ppDevicesList, const char* addr, const uint16_t port,
90                                OCTransportAdapter adapter, OCConnectivityType connType, OicSecDoxm_t *doxm)
91 {
92     if (NULL == addr)
93     {
94         return OC_STACK_INVALID_PARAM;
95     }
96
97     OCProvisionDev_t *ptr = GetDevice(ppDevicesList, addr, port);
98     if(!ptr)
99     {
100         ptr = (OCProvisionDev_t *)OICCalloc(1, sizeof (OCProvisionDev_t));
101         if (NULL == ptr)
102         {
103             OC_LOG(ERROR, TAG, "Error while allocating memory for linkedlist node !!");
104             return OC_STACK_NO_MEMORY;
105         }
106
107         OICStrcpy(ptr->endpoint.addr, MAX_ADDR_STR_SIZE, addr);
108         ptr->endpoint.port = port;
109         ptr->doxm = doxm;
110         ptr->securePort = DEFAULT_SECURE_PORT;
111         ptr->endpoint.adapter = adapter;
112         ptr->next = NULL;
113         ptr->connType = connType;
114
115         LL_PREPEND(*ppDevicesList, ptr);
116     }
117
118     return OC_STACK_OK;
119 }
120
121 /**
122  * Function to set secure port information from the given list of devices.
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  * @param[in] secureport    secure port information.
128  *
129  * @return OC_STACK_OK for success and errorcode otherwise.
130  */
131 OCStackResult UpdateSecurePortOfDevice(OCProvisionDev_t **ppDevicesList, const char *addr, uint16_t port,
132                                         uint16_t securePort)
133 {
134     OCProvisionDev_t *ptr = GetDevice(ppDevicesList, addr, port);
135
136     if(!ptr)
137     {
138         OC_LOG(ERROR, TAG, "Can not find device information in the discovery device list");
139         return OC_STACK_ERROR;
140     }
141
142     ptr->securePort = securePort;
143
144     return OC_STACK_OK;
145 }
146
147 /**
148  * This function deletes list of provision target devices
149  *
150  * @param[in] pList         List of OCProvisionDev_t.
151  */
152 void DeleteDeviceList(OCProvisionDev_t **ppDevicesList)
153 {
154     if(*ppDevicesList)
155     {
156         OCProvisionDev_t *del = NULL, *tmp = NULL;
157         LL_FOREACH_SAFE(*ppDevicesList, del, tmp)
158         {
159             LL_DELETE(*ppDevicesList, del);
160
161             DeleteDoxmBinData(del->doxm);
162             DeletePstatBinData(del->pstat);
163             OICFree(del);
164         }
165     }
166 }
167
168 /**
169  * Timeout implementation for secure discovery. When performing secure discovery,
170  * we should wait a certain period of time for getting response of each devices.
171  *
172  * @param[in]  waittime  Timeout in seconds.
173  * @return OC_STACK_OK on success otherwise error.
174  */
175 OCStackResult PMTimeout(unsigned short waittime)
176 {
177     struct timespec startTime = {.tv_sec=0, .tv_nsec=0};
178     struct timespec currTime  = {.tv_sec=0, .tv_nsec=0};
179
180     OCStackResult res = OC_STACK_OK;
181 #ifdef _POSIX_MONOTONIC_CLOCK
182     int clock_res = clock_gettime(CLOCK_MONOTONIC, &startTime);
183 #else
184     int clock_res = clock_gettime(CLOCK_REALTIME, &startTime);
185 #endif
186     if (0 != clock_res)
187     {
188         return OC_STACK_ERROR;
189     }
190     while (OC_STACK_OK == res)
191     {
192 #ifdef _POSIX_MONOTONIC_CLOCK
193         clock_res = clock_gettime(CLOCK_MONOTONIC, &currTime);
194 #else
195         clock_res = clock_gettime(CLOCK_REALTIME, &currTime);
196 #endif
197         if (0 != clock_res)
198         {
199             return OC_STACK_TIMEOUT;
200         }
201         long elapsed = (currTime.tv_sec - startTime.tv_sec);
202         if (elapsed > waittime)
203         {
204             return OC_STACK_OK;
205         }
206         res = OCProcess();
207     }
208
209     return res;
210 }
211
212 /**
213  * Extract secure port information from payload of discovery response.
214  *
215  * @param[in] jsonStr response payload of /oic/res discovery.
216  *
217  * @return Secure port
218  */
219 uint16_t GetSecurePortFromJSON(char* jsonStr)
220 {
221     // TODO: Modify error handling
222     if (NULL == jsonStr)
223     {
224         return 0;
225     }
226     cJSON *jsonProp = NULL;
227     cJSON *jsonP = NULL;
228     cJSON *jsonPort = NULL;
229
230     cJSON *jsonRoot = cJSON_Parse(jsonStr);
231     if(!jsonRoot)
232     {
233         // TODO: Add error log & return default secure port
234         return 0;
235     }
236
237     jsonProp = cJSON_GetObjectItem(jsonRoot, "prop");
238     if(!jsonProp)
239     {
240         // TODO: Add error log & return default secure port
241         return 0;
242     }
243
244     jsonP = cJSON_GetObjectItem(jsonProp, "p");
245     if(!jsonP)
246     {
247         // TODO: Add error log & return default secure port
248         return 0;
249     }
250
251     jsonPort = cJSON_GetObjectItem(jsonP, "port");
252     if(!jsonPort)
253     {
254         // TODO: Add error log & return default secure port
255         return 0;
256     }
257
258     return (uint16_t)jsonPort->valueint;
259 }
260
261 bool PMGenerateQuery(bool isSecure,
262                      const char* address, const uint16_t port,
263                      const OCConnectivityType connType,
264                      char* buffer, size_t bufferSize, const char* uri)
265 {
266     if(!address || !buffer || !uri)
267     {
268         OC_LOG(ERROR, TAG, "PMGenerateQuery : Invalid parameters.");
269         return false;
270     }
271
272     int snRet = 0;
273     char* prefix = (isSecure == true) ? COAPS_PREFIX : COAP_PREFIX;
274
275     switch(connType & CT_MASK_ADAPTER)
276     {
277         case CT_ADAPTER_IP:
278             switch(connType & CT_MASK_FLAGS)
279             {
280                 case CT_IP_USE_V4:
281                         snRet = snprintf(buffer, bufferSize, "%s%s:%d%s",
282                                          prefix, address, port, uri);
283                     break;
284                 case CT_IP_USE_V6:
285                         snRet = snprintf(buffer, bufferSize, "%s[%s]:%d%s",
286                                          prefix, address, port, uri);
287                     break;
288                 default:
289                     OC_LOG(ERROR, ERROR, "Unknown address format.");
290                     return false;
291             }
292             if(snRet >= bufferSize)
293             {
294                 OC_LOG(ERROR, INFO, "PMGenerateQuery : URI is too long");
295                 return false;
296             }
297             break;
298         // TODO: We need to verify tinyDTLS in below cases
299         case CT_ADAPTER_GATT_BTLE:
300         case CT_ADAPTER_RFCOMM_BTEDR:
301             OC_LOG(ERROR, ERROR, "Not supported connectivity adapter.");
302             return false;
303             break;
304         default:
305             OC_LOG(ERROR, ERROR, "Unknown connectivity adapter.");
306             return false;
307     }
308
309     return true;
310 }
311
312 /**
313  * Callback handler for getting secure port information using /oic/res discovery.
314  *
315  * @param[in] ctx             user context
316  * @param[in] handle          Handle for response
317  * @param[in] clientResponse  Response information(It will contain payload)
318  *
319  * @return OC_STACK_KEEP_TRANSACTION to keep transaction and
320  *         OC_STACK_DELETE_TRANSACTION to delete it.
321  */
322 static OCStackApplicationResult SecurePortDiscoveryHandler(void *ctx, OCDoHandle UNUSED,
323                                  OCClientResponse *clientResponse)
324 {
325     if (ctx == NULL)
326     {
327         OC_LOG(ERROR, TAG, "Lost List of device information");
328         return OC_STACK_KEEP_TRANSACTION;
329     }
330     (void)UNUSED;
331     if (clientResponse)
332     {
333         if  (NULL == clientResponse->payload)
334         {
335             OC_LOG(INFO, TAG, "Skiping Null payload");
336         }
337         else
338         {
339             if (PAYLOAD_TYPE_DISCOVERY != clientResponse->payload->type)
340             {
341                 OC_LOG(INFO, TAG, "Wrong payload type");
342                 return OC_STACK_KEEP_TRANSACTION;
343             }
344
345             uint16_t securePort = 0;
346             OCResourcePayload* resPayload = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
347
348             if (resPayload && resPayload->secure)
349             {
350                 securePort = resPayload->port;
351             }
352             else
353             {
354                 OC_LOG(INFO, TAG, "Can not find secure port information.");
355                 return OC_STACK_KEEP_TRANSACTION;
356             }
357
358             OCProvisionDev_t** ppDevicesList = (OCProvisionDev_t**) ctx;
359
360             OCStackResult res = UpdateSecurePortOfDevice(ppDevicesList, clientResponse->devAddr.addr,
361                                                          clientResponse->devAddr.port, securePort);
362             if (OC_STACK_OK != res)
363             {
364                 OC_LOG(ERROR, TAG, "Error while getting secure port.");
365                 return OC_STACK_KEEP_TRANSACTION;
366             }
367             OC_LOG(INFO, TAG, "Exiting SecurePortDiscoveryHandler.");
368         }
369
370         return  OC_STACK_KEEP_TRANSACTION;
371     }
372     else
373     {
374         OC_LOG(INFO, TAG, "Skiping Null response");
375     }
376     return  OC_STACK_DELETE_TRANSACTION;
377 }
378
379 /**
380  * Callback handler for PMDeviceDiscovery API.
381  *
382  * @param[in] ctx             User context
383  * @param[in] handle          Handler for response
384  * @param[in] clientResponse  Response information (It will contain payload)
385  * @return OC_STACK_KEEP_TRANSACTION to keep transaction and
386  *         OC_STACK_DELETE_TRANSACTION to delete it.
387  */
388 static OCStackApplicationResult DeviceDiscoveryHandler(void *ctx, OCDoHandle UNUSED,
389                                 OCClientResponse *clientResponse)
390 {
391     if (ctx == NULL)
392     {
393         OC_LOG(ERROR, TAG, "Lost List of device information");
394         return OC_STACK_KEEP_TRANSACTION;
395     }
396     (void)UNUSED;
397     if (clientResponse)
398     {
399         if  (NULL == clientResponse->payload)
400         {
401             OC_LOG(INFO, TAG, "Skiping Null payload");
402             return OC_STACK_KEEP_TRANSACTION;
403         }
404         if (OC_STACK_OK != clientResponse->result)
405         {
406             OC_LOG(INFO, TAG, "Error in response");
407             return OC_STACK_KEEP_TRANSACTION;
408         }
409         else
410         {
411             if (PAYLOAD_TYPE_SECURITY != clientResponse->payload->type)
412             {
413                 OC_LOG(INFO, TAG, "Unknown payload type");
414                 return OC_STACK_KEEP_TRANSACTION;
415             }
416             OicSecDoxm_t *ptrDoxm = JSONToDoxmBin(
417                             ((OCSecurityPayload*)clientResponse->payload)->securityData);
418             if (NULL == ptrDoxm)
419             {
420                 OC_LOG(INFO, TAG, "Ignoring malformed JSON");
421                 return OC_STACK_KEEP_TRANSACTION;
422             }
423             else
424             {
425                 OC_LOG(DEBUG, TAG, "Successfully converted doxm json to bin.");
426
427                 OCProvisionDev_t **ppDevicesList = (OCProvisionDev_t**) ctx;
428
429                 OCStackResult res = AddDevice(ppDevicesList, clientResponse->devAddr.addr,
430                         clientResponse->devAddr.port,
431                         clientResponse->devAddr.adapter,
432                         clientResponse->connType, ptrDoxm);
433                 if (OC_STACK_OK != res)
434                 {
435                     OC_LOG(ERROR, TAG, "Error while adding data to linkedlist.");
436                     DeleteDoxmBinData(ptrDoxm);
437                     return OC_STACK_KEEP_TRANSACTION;
438                 }
439
440                 //Try to the unicast discovery to getting secure port
441                 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = { 0, };
442                 if(!PMGenerateQuery(false,
443                                     clientResponse->devAddr.addr, clientResponse->devAddr.port,
444                                     clientResponse->connType,
445                                     query, sizeof(query), OC_RSRVD_WELL_KNOWN_URI))
446                 {
447                     OC_LOG(ERROR, TAG, "DeviceDiscoveryHandler : Failed to generate query");
448                     return OC_STACK_ERROR;
449                 }
450                 OC_LOG_V(DEBUG, TAG, "Query=%s", query);
451
452                 OCCallbackData cbData;
453                 cbData.cb = &SecurePortDiscoveryHandler;
454                 cbData.context = ctx;
455                 cbData.cd = NULL;
456                 OCStackResult ret = OCDoResource(NULL, OC_REST_GET, query, 0, 0,
457                         clientResponse->connType, OC_LOW_QOS, &cbData, NULL, 0);
458                 // TODO: Should we use the default secure port in case of error?
459                 if(OC_STACK_OK != ret)
460                 {
461                     OC_LOG(ERROR, TAG, "Failed to Secure Port Discovery");
462                     return OC_STACK_DELETE_TRANSACTION;
463                 }
464                 else
465                 {
466                     OC_LOG_V(INFO, TAG, "OCDoResource with [%s] Success", query);
467                 }
468                 OC_LOG(INFO, TAG, "Exiting ProvisionDiscoveryHandler.");
469             }
470
471             return  OC_STACK_KEEP_TRANSACTION;
472         }
473     }
474     else
475     {
476         OC_LOG(INFO, TAG, "Skiping Null response");
477         return OC_STACK_KEEP_TRANSACTION;
478     }
479
480     return  OC_STACK_DELETE_TRANSACTION;
481 }
482
483 /**
484  * Discover owned/unowned devices in the same IP subnet. .
485  *
486  * @param[in] waittime      Timeout in seconds.
487  * @param[in] isOwned       bool flag for owned / unowned discovery
488  * @param[in] ppDevicesList        List of OCProvisionDev_t.
489  *
490  * @return OC_STACK_OK on success otherwise error.
491  */
492 OCStackResult PMDeviceDiscovery(unsigned short waittime, bool isOwned, OCProvisionDev_t **ppDevicesList)
493 {
494     OC_LOG(DEBUG, TAG, "IN PMDeviceDiscovery");
495
496     if (NULL != *ppDevicesList)
497     {
498         OC_LOG(ERROR, TAG, "List is not null can cause memory leak");
499         return OC_STACK_INVALID_PARAM;
500     }
501
502     const char DOXM_OWNED_FALSE_MULTICAST_QUERY[] = "/oic/sec/doxm?Owned=FALSE";
503     const char DOXM_OWNED_TRUE_MULTICAST_QUERY[] = "/oic/sec/doxm?Owned=TRUE";
504
505     OCCallbackData cbData;
506     cbData.cb = &DeviceDiscoveryHandler;
507     cbData.context = (void *)ppDevicesList;
508     cbData.cd = NULL;
509     OCStackResult res = OC_STACK_ERROR;
510
511     const char* query = isOwned ? DOXM_OWNED_TRUE_MULTICAST_QUERY :
512                                   DOXM_OWNED_FALSE_MULTICAST_QUERY;
513
514     res = OCDoResource(NULL, OC_REST_DISCOVER, query, 0, 0,
515                                      CT_DEFAULT, OC_LOW_QOS, &cbData, NULL, 0);
516     if (res != OC_STACK_OK)
517     {
518         OC_LOG(ERROR, TAG, "OCStack resource error");
519         goto exit;
520     }
521
522     //Waiting for each response.
523     res = PMTimeout(waittime);
524     if(OC_STACK_OK != res)
525     {
526         OC_LOG(ERROR, TAG, "Failed to wait response for secure discovery.");
527         goto exit;
528     }
529
530     OC_LOG(DEBUG, TAG, "OUT PMDeviceDiscovery");
531 exit:
532     return res;
533 }