Add PIN based OxM for security provisioning
[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,
271                                 OCDoHandle UNUSED, 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
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,
337                                 OCDoHandle UNUSED, 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     if (clientResponse)
345     {
346         if  (NULL == clientResponse->payload)
347         {
348             OC_LOG(INFO, TAG, "Skiping Null payload");
349             return OC_STACK_KEEP_TRANSACTION;
350         }
351         if (OC_STACK_OK != clientResponse->result)
352         {
353             OC_LOG(INFO, TAG, "Error in response");
354             return OC_STACK_KEEP_TRANSACTION;
355         }
356         else
357         {
358             if (PAYLOAD_TYPE_SECURITY != clientResponse->payload->type)
359             {
360                 OC_LOG(INFO, TAG, "Unknown payload type");
361                 return OC_STACK_KEEP_TRANSACTION;
362             }
363             OicSecDoxm_t *ptrDoxm = JSONToDoxmBin(
364                             ((OCSecurityPayload*)clientResponse->payload)->securityData);
365             if (NULL == ptrDoxm)
366             {
367                 OC_LOG(INFO, TAG, "Ignoring malformed JSON");
368                 return OC_STACK_KEEP_TRANSACTION;
369             }
370             else
371             {
372                 OC_LOG(DEBUG, TAG, "Successfully converted doxm json to bin.");
373
374                 OCProvisionDev_t **ppDevicesList = (OCProvisionDev_t**) ctx;
375
376                 OCStackResult res = AddDevice(ppDevicesList, clientResponse->devAddr.addr,
377                         clientResponse->devAddr.port,
378                         clientResponse->devAddr.adapter, ptrDoxm);
379                 if (OC_STACK_OK != res)
380                 {
381                     OC_LOG(ERROR, TAG, "Error while adding data to linkedlist.");
382                     DeleteDoxmBinData(ptrDoxm);
383                     return OC_STACK_KEEP_TRANSACTION;
384                 }
385
386                 //Try to the unicast discovery to getting secure port
387                 char query[MAX_QUERY_LENGTH] = { 0, };
388                 sprintf(query, "%s%s:%d%s",
389                         COAP_PREFIX,
390                         clientResponse->devAddr.addr, clientResponse->devAddr.port,
391                         OC_RSRVD_WELL_KNOWN_URI);
392
393                 OCCallbackData cbData;
394                 cbData.cb = &SecurePortDiscoveryHandler;
395                 cbData.context = ctx;
396                 cbData.cd = NULL;
397                 OCStackResult ret = OCDoResource(NULL, OC_REST_GET, query, 0, 0,
398                         CT_ADAPTER_IP, OC_LOW_QOS, &cbData, NULL, 0);
399                 // TODO: Should we use the default secure port in case of error?
400                 if(OC_STACK_OK != ret)
401                 {
402                     UpdateSecurePortOfDevice(ppDevicesList, clientResponse->devAddr.addr,
403                             clientResponse->devAddr.port, DEFAULT_SECURE_PORT);
404                 }
405                 else
406                 {
407                     OC_LOG_V(ERROR, TAG, "OCDoResource with [%s] Success", query);
408                 }
409                 OC_LOG(INFO, TAG, "Exiting ProvisionDiscoveryHandler.");
410             }
411
412             return  OC_STACK_KEEP_TRANSACTION;
413         }
414     }
415     else
416     {
417         OC_LOG(INFO, TAG, "Skiping Null response");
418         return OC_STACK_KEEP_TRANSACTION;
419     }
420
421     return  OC_STACK_DELETE_TRANSACTION;
422 }
423
424 /**
425  * Discover owned/unowned devices in the same IP subnet. .
426  *
427  * @param[in] waittime      Timeout in seconds.
428  * @param[in] isOwned       bool flag for owned / unowned discovery
429  * @param[in] ppDevicesList        List of OCProvisionDev_t.
430  *
431  * @return OC_STACK_OK on success otherwise error.
432  */
433 OCStackResult PMDeviceDiscovery(unsigned short waittime, bool isOwned, OCProvisionDev_t **ppDevicesList)
434 {
435     OC_LOG(DEBUG, TAG, "IN PMDeviceDiscovery");
436
437     if (NULL != *ppDevicesList)
438     {
439         OC_LOG(ERROR, TAG, "List is not null can cause memory leak");
440         return OC_STACK_INVALID_PARAM;
441     }
442
443     const char DOXM_OWNED_FALSE_MULTICAST_QUERY[] = "/oic/sec/doxm?Owned=FALSE";
444     const char DOXM_OWNED_TRUE_MULTICAST_QUERY[] = "/oic/sec/doxm?Owned=TRUE";
445
446     OCCallbackData cbData;
447     cbData.cb = &DeviceDiscoveryHandler;
448     cbData.context = (void *)ppDevicesList;
449     cbData.cd = NULL;
450     OCStackResult res = OC_STACK_ERROR;
451
452     const char* query = isOwned ? DOXM_OWNED_TRUE_MULTICAST_QUERY :
453                                   DOXM_OWNED_FALSE_MULTICAST_QUERY;
454
455     res = OCDoResource(NULL, OC_REST_DISCOVER, query, 0, 0,
456                                      CT_DEFAULT, OC_LOW_QOS, &cbData, NULL, 0);
457     if (res != OC_STACK_OK)
458     {
459         OC_LOG(ERROR, TAG, "OCStack resource error");
460         goto exit;
461     }
462
463     //Waiting for each response.
464     res = PMTimeout(waittime);
465     if(OC_STACK_OK != res)
466     {
467         OC_LOG(ERROR, TAG, "Failed to wait response for secure discovery.");
468         goto exit;
469     }
470
471     OC_LOG(DEBUG, TAG, "OUT PMDeviceDiscovery");
472 exit:
473     return res;
474 }