Merge branch 'master' into easysetup & CBOR changes
[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  *
86  * @return OC_STACK_OK for success and errorcode otherwise.
87  */
88 OCStackResult AddDevice(OCProvisionDev_t **ppDevicesList, const char* addr, const uint16_t port,
89                                OCTransportAdapter adapter, OicSecDoxm_t *doxm)
90 {
91     if (NULL == addr)
92     {
93         return OC_STACK_INVALID_PARAM;
94     }
95
96     OCProvisionDev_t *ptr = GetDevice(ppDevicesList, addr, port);
97     if(!ptr)
98     {
99         ptr = (OCProvisionDev_t *)OICCalloc(1, sizeof (OCProvisionDev_t));
100         if (NULL == ptr)
101         {
102             OC_LOG(ERROR, TAG, "Error while allocating memory for linkedlist node !!");
103             return OC_STACK_NO_MEMORY;
104         }
105
106         OICStrcpy(ptr->endpoint.addr, MAX_ADDR_STR_SIZE, addr);
107         ptr->endpoint.port = port;
108         ptr->doxm = doxm;
109         ptr->securePort = DEFAULT_SECURE_PORT;
110         ptr->endpoint.adapter = adapter;
111         ptr->next = NULL;
112
113         LL_PREPEND(*ppDevicesList, ptr);
114     }
115
116     return OC_STACK_OK;
117 }
118
119 /**
120  * Function to set secure port information from the given list of devices.
121  *
122  * @param[in] pList         List of OCProvisionDev_t.
123  * @param[in] addr          address of target device.
124  * @param[in] port          port of remote server.
125  * @param[in] secureport    secure port information.
126  *
127  * @return OC_STACK_OK for success and errorcode otherwise.
128  */
129 OCStackResult UpdateSecurePortOfDevice(OCProvisionDev_t **ppDevicesList, const char *addr, uint16_t port,
130                                         uint16_t securePort)
131 {
132     OCProvisionDev_t *ptr = GetDevice(ppDevicesList, addr, port);
133
134     if(!ptr)
135     {
136         OC_LOG(ERROR, TAG, "Can not find device information in the discovery device list");
137         return OC_STACK_ERROR;
138     }
139
140     ptr->securePort = securePort;
141
142     return OC_STACK_OK;
143 }
144
145 /**
146  * This function deletes list of provision target devices
147  *
148  * @param[in] pList         List of OCProvisionDev_t.
149  */
150 void DeleteDeviceList(OCProvisionDev_t **ppDevicesList)
151 {
152     if(*ppDevicesList)
153     {
154         OCProvisionDev_t *del = NULL, *tmp = NULL;
155         LL_FOREACH_SAFE(*ppDevicesList, del, tmp)
156         {
157             LL_DELETE(*ppDevicesList, del);
158
159             DeleteDoxmBinData(del->doxm);
160             DeletePstatBinData(del->pstat);
161             OICFree(del);
162         }
163     }
164 }
165
166 /**
167  * Timeout implementation for secure discovery. When performing secure discovery,
168  * we should wait a certain period of time for getting response of each devices.
169  *
170  * @param[in]  waittime  Timeout in seconds.
171  * @return OC_STACK_OK on success otherwise error.
172  */
173 OCStackResult PMTimeout(unsigned short waittime)
174 {
175     struct timespec startTime = {.tv_sec=0, .tv_nsec=0};
176     struct timespec currTime  = {.tv_sec=0, .tv_nsec=0};
177
178     OCStackResult res = OC_STACK_OK;
179 #ifdef _POSIX_MONOTONIC_CLOCK
180     int clock_res = clock_gettime(CLOCK_MONOTONIC, &startTime);
181 #else
182     int clock_res = clock_gettime(CLOCK_REALTIME, &startTime);
183 #endif
184     if (0 != clock_res)
185     {
186         return OC_STACK_ERROR;
187     }
188     while (OC_STACK_OK == res)
189     {
190 #ifdef _POSIX_MONOTONIC_CLOCK
191         clock_res = clock_gettime(CLOCK_MONOTONIC, &currTime);
192 #else
193         clock_res = clock_gettime(CLOCK_REALTIME, &currTime);
194 #endif
195         if (0 != clock_res)
196         {
197             return OC_STACK_TIMEOUT;
198         }
199         long elapsed = (currTime.tv_sec - startTime.tv_sec);
200         if (elapsed > waittime)
201         {
202             return OC_STACK_OK;
203         }
204         res = OCProcess();
205     }
206
207     return res;
208 }
209
210 /**
211  * Extract secure port information from payload of discovery response.
212  *
213  * @param[in] jsonStr response payload of /oic/res discovery.
214  *
215  * @return Secure port
216  */
217 uint16_t GetSecurePortFromJSON(char* jsonStr)
218 {
219     // TODO: Modify error handling
220     if (NULL == jsonStr)
221     {
222         return 0;
223     }
224     cJSON *jsonProp = NULL;
225     cJSON *jsonP = NULL;
226     cJSON *jsonPort = NULL;
227
228     cJSON *jsonRoot = cJSON_Parse(jsonStr);
229     if(!jsonRoot)
230     {
231         // TODO: Add error log & return default secure port
232         return 0;
233     }
234
235     jsonProp = cJSON_GetObjectItem(jsonRoot, "prop");
236     if(!jsonProp)
237     {
238         // TODO: Add error log & return default secure port
239         return 0;
240     }
241
242     jsonP = cJSON_GetObjectItem(jsonProp, "p");
243     if(!jsonP)
244     {
245         // TODO: Add error log & return default secure port
246         return 0;
247     }
248
249     jsonPort = cJSON_GetObjectItem(jsonP, "port");
250     if(!jsonPort)
251     {
252         // TODO: Add error log & return default secure port
253         return 0;
254     }
255
256     return (uint16_t)jsonPort->valueint;
257 }
258
259
260 /**
261  * Callback handler for getting secure port information using /oic/res discovery.
262  *
263  * @param[in] ctx             user context
264  * @param[in] handle          Handle for response
265  * @param[in] clientResponse  Response information(It will contain payload)
266  *
267  * @return OC_STACK_KEEP_TRANSACTION to keep transaction and
268  *         OC_STACK_DELETE_TRANSACTION to delete it.
269  */
270 static OCStackApplicationResult SecurePortDiscoveryHandler(void *ctx, OCDoHandle UNUSED,
271                                  OCClientResponse *clientResponse)
272 {
273     if (ctx == NULL)
274     {
275         OC_LOG(ERROR, TAG, "Lost List of device information");
276         return OC_STACK_KEEP_TRANSACTION;
277     }
278     (void)UNUSED;
279     if (clientResponse)
280     {
281         if  (NULL == clientResponse->payload)
282         {
283             OC_LOG(INFO, TAG, "Skiping Null payload");
284         }
285         else
286         {
287             if (PAYLOAD_TYPE_DISCOVERY != clientResponse->payload->type)
288             {
289                 OC_LOG(INFO, TAG, "Wrong payload type");
290                 return OC_STACK_KEEP_TRANSACTION;
291             }
292
293             OCDiscoveryPayload* discover = (OCDiscoveryPayload*) clientResponse->payload;
294             uint16_t securePort = 0;
295
296             if (discover && discover->resources && discover->resources->secure)
297             {
298                 securePort = discover->resources->port;
299             }
300             else
301             {
302                 OC_LOG(INFO, TAG, "Secure Port info is missing");
303                 return OC_STACK_KEEP_TRANSACTION;
304             }
305
306             OCProvisionDev_t** ppDevicesList = (OCProvisionDev_t**) ctx;
307
308             OCStackResult res = UpdateSecurePortOfDevice(ppDevicesList, clientResponse->devAddr.addr,
309                                                          clientResponse->devAddr.port, securePort);
310             if (OC_STACK_OK != res)
311             {
312                 OC_LOG(ERROR, TAG, "Error while getting secure port.");
313                 return OC_STACK_KEEP_TRANSACTION;
314             }
315             OC_LOG(INFO, TAG, "Exiting SecurePortDiscoveryHandler.");
316         }
317
318         return  OC_STACK_KEEP_TRANSACTION;
319     }
320     else
321     {
322         OC_LOG(INFO, TAG, "Skiping Null response");
323     }
324     return  OC_STACK_DELETE_TRANSACTION;
325 }
326
327 /**
328  * Callback handler for PMDeviceDiscovery API.
329  *
330  * @param[in] ctx             User context
331  * @param[in] handle          Handler for response
332  * @param[in] clientResponse  Response information (It will contain payload)
333  * @return OC_STACK_KEEP_TRANSACTION to keep transaction and
334  *         OC_STACK_DELETE_TRANSACTION to delete it.
335  */
336 static OCStackApplicationResult DeviceDiscoveryHandler(void *ctx, OCDoHandle UNUSED,
337                                 OCClientResponse *clientResponse)
338 {
339     if (ctx == NULL)
340     {
341         OC_LOG(ERROR, TAG, "Lost List of device information");
342         return OC_STACK_KEEP_TRANSACTION;
343     }
344     (void)UNUSED;
345     if (clientResponse)
346     {
347         if  (NULL == clientResponse->payload)
348         {
349             OC_LOG(INFO, TAG, "Skiping Null payload");
350             return OC_STACK_KEEP_TRANSACTION;
351         }
352         if (OC_STACK_OK != clientResponse->result)
353         {
354             OC_LOG(INFO, TAG, "Error in response");
355             return OC_STACK_KEEP_TRANSACTION;
356         }
357         else
358         {
359             if (PAYLOAD_TYPE_SECURITY != clientResponse->payload->type)
360             {
361                 OC_LOG(INFO, TAG, "Unknown payload type");
362                 return OC_STACK_KEEP_TRANSACTION;
363             }
364             OicSecDoxm_t *ptrDoxm = JSONToDoxmBin(
365                             ((OCSecurityPayload*)clientResponse->payload)->securityData);
366             if (NULL == ptrDoxm)
367             {
368                 OC_LOG(INFO, TAG, "Ignoring malformed JSON");
369                 return OC_STACK_KEEP_TRANSACTION;
370             }
371             else
372             {
373                 OC_LOG(DEBUG, TAG, "Successfully converted doxm json to bin.");
374
375                 OCProvisionDev_t **ppDevicesList = (OCProvisionDev_t**) ctx;
376
377                 OCStackResult res = AddDevice(ppDevicesList, clientResponse->devAddr.addr,
378                         clientResponse->devAddr.port,
379                         clientResponse->devAddr.adapter, ptrDoxm);
380                 if (OC_STACK_OK != res)
381                 {
382                     OC_LOG(ERROR, TAG, "Error while adding data to linkedlist.");
383                     DeleteDoxmBinData(ptrDoxm);
384                     return OC_STACK_KEEP_TRANSACTION;
385                 }
386
387                 //Try to the unicast discovery to getting secure port
388                 char query[MAX_QUERY_LENGTH] = { 0, };
389                 sprintf(query, "%s%s:%d%s",
390                         COAP_PREFIX,
391                         clientResponse->devAddr.addr, clientResponse->devAddr.port,
392                         OC_RSRVD_WELL_KNOWN_URI);
393
394                 OCCallbackData cbData;
395                 cbData.cb = &SecurePortDiscoveryHandler;
396                 cbData.context = ctx;
397                 cbData.cd = NULL;
398                 OCStackResult ret = OCDoResource(NULL, OC_REST_GET, query, 0, 0,
399                         CT_ADAPTER_IP, OC_LOW_QOS, &cbData, NULL, 0);
400                 // TODO: Should we use the default secure port in case of error?
401                 if(OC_STACK_OK != ret)
402                 {
403                     UpdateSecurePortOfDevice(ppDevicesList, clientResponse->devAddr.addr,
404                             clientResponse->devAddr.port, DEFAULT_SECURE_PORT);
405                 }
406                 else
407                 {
408                     OC_LOG_V(ERROR, TAG, "OCDoResource with [%s] Success", query);
409                 }
410                 OC_LOG(INFO, TAG, "Exiting ProvisionDiscoveryHandler.");
411             }
412
413             return  OC_STACK_KEEP_TRANSACTION;
414         }
415     }
416     else
417     {
418         OC_LOG(INFO, TAG, "Skiping Null response");
419         return OC_STACK_KEEP_TRANSACTION;
420     }
421
422     return  OC_STACK_DELETE_TRANSACTION;
423 }
424
425 /**
426  * Discover owned/unowned devices in the same IP subnet. .
427  *
428  * @param[in] waittime      Timeout in seconds.
429  * @param[in] isOwned       bool flag for owned / unowned discovery
430  * @param[in] ppDevicesList        List of OCProvisionDev_t.
431  *
432  * @return OC_STACK_OK on success otherwise error.
433  */
434 OCStackResult PMDeviceDiscovery(unsigned short waittime, bool isOwned, OCProvisionDev_t **ppDevicesList)
435 {
436     OC_LOG(DEBUG, TAG, "IN PMDeviceDiscovery");
437
438     if (NULL != *ppDevicesList)
439     {
440         OC_LOG(ERROR, TAG, "List is not null can cause memory leak");
441         return OC_STACK_INVALID_PARAM;
442     }
443
444     const char DOXM_OWNED_FALSE_MULTICAST_QUERY[] = "/oic/sec/doxm?Owned=FALSE";
445     const char DOXM_OWNED_TRUE_MULTICAST_QUERY[] = "/oic/sec/doxm?Owned=TRUE";
446
447     OCCallbackData cbData;
448     cbData.cb = &DeviceDiscoveryHandler;
449     cbData.context = (void *)ppDevicesList;
450     cbData.cd = NULL;
451     OCStackResult res = OC_STACK_ERROR;
452
453     const char* query = isOwned ? DOXM_OWNED_TRUE_MULTICAST_QUERY :
454                                   DOXM_OWNED_FALSE_MULTICAST_QUERY;
455
456     res = OCDoResource(NULL, OC_REST_DISCOVER, query, 0, 0,
457                                      CT_DEFAULT, OC_LOW_QOS, &cbData, NULL, 0);
458     if (res != OC_STACK_OK)
459     {
460         OC_LOG(ERROR, TAG, "OCStack resource error");
461         goto exit;
462     }
463
464     //Waiting for each response.
465     res = PMTimeout(waittime);
466     if(OC_STACK_OK != res)
467     {
468         OC_LOG(ERROR, TAG, "Failed to wait response for secure discovery.");
469         goto exit;
470     }
471
472     OC_LOG(DEBUG, TAG, "OUT PMDeviceDiscovery");
473 exit:
474     return res;
475 }