Add security payload type to a request/response
[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             OC_LOG_V(INFO, TAG, "UpdateSecurePortOfDevice with %d",  securePort);
360
361             OCStackResult res = UpdateSecurePortOfDevice(ppDevicesList, clientResponse->devAddr.addr,
362                                                          clientResponse->devAddr.port, securePort);
363             if (OC_STACK_OK != res)
364             {
365                 OC_LOG(ERROR, TAG, "Error while getting secure port.");
366                 return OC_STACK_KEEP_TRANSACTION;
367             }
368             OC_LOG(INFO, TAG, "Exiting SecurePortDiscoveryHandler.");
369         }
370
371         return  OC_STACK_KEEP_TRANSACTION;
372     }
373     else
374     {
375         OC_LOG(INFO, TAG, "Skiping Null response");
376     }
377     return  OC_STACK_DELETE_TRANSACTION;
378 }
379
380 /**
381  * Callback handler for PMDeviceDiscovery API.
382  *
383  * @param[in] ctx             User context
384  * @param[in] handle          Handler for response
385  * @param[in] clientResponse  Response information (It will contain payload)
386  * @return OC_STACK_KEEP_TRANSACTION to keep transaction and
387  *         OC_STACK_DELETE_TRANSACTION to delete it.
388  */
389 static OCStackApplicationResult DeviceDiscoveryHandler(void *ctx, OCDoHandle UNUSED,
390                                 OCClientResponse *clientResponse)
391 {
392     if (ctx == NULL)
393     {
394         OC_LOG(ERROR, TAG, "Lost List of device information");
395         return OC_STACK_KEEP_TRANSACTION;
396     }
397     (void)UNUSED;
398     if (clientResponse)
399     {
400         if  (NULL == clientResponse->payload)
401         {
402             OC_LOG(INFO, TAG, "Skiping Null payload");
403             return OC_STACK_KEEP_TRANSACTION;
404         }
405         if (OC_STACK_OK != clientResponse->result)
406         {
407             OC_LOG(INFO, TAG, "Error in response");
408             return OC_STACK_KEEP_TRANSACTION;
409         }
410         else
411         {
412             if (PAYLOAD_TYPE_SECURITY != clientResponse->payload->type)
413             {
414                 OC_LOG(INFO, TAG, "Unknown payload type");
415                 return OC_STACK_KEEP_TRANSACTION;
416             }
417             OicSecDoxm_t *ptrDoxm = JSONToDoxmBin(
418                             ((OCSecurityPayload*)clientResponse->payload)->securityData);
419             if (NULL == ptrDoxm)
420             {
421                 OC_LOG(INFO, TAG, "Ignoring malformed JSON");
422                 return OC_STACK_KEEP_TRANSACTION;
423             }
424             else
425             {
426                 OC_LOG(DEBUG, TAG, "Successfully converted doxm json to bin.");
427
428                 OCProvisionDev_t **ppDevicesList = (OCProvisionDev_t**) ctx;
429
430                 OCStackResult res = AddDevice(ppDevicesList, clientResponse->devAddr.addr,
431                         clientResponse->devAddr.port,
432                         clientResponse->devAddr.adapter,
433                         clientResponse->connType, ptrDoxm);
434                 if (OC_STACK_OK != res)
435                 {
436                     OC_LOG(ERROR, TAG, "Error while adding data to linkedlist.");
437                     DeleteDoxmBinData(ptrDoxm);
438                     return OC_STACK_KEEP_TRANSACTION;
439                 }
440
441                 //Try to the unicast discovery to getting secure port
442                 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = { 0, };
443                 if(!PMGenerateQuery(false,
444                                     clientResponse->devAddr.addr, clientResponse->devAddr.port,
445                                     clientResponse->connType,
446                                     query, sizeof(query), OC_RSRVD_WELL_KNOWN_URI))
447                 {
448                     OC_LOG(ERROR, TAG, "DeviceDiscoveryHandler : Failed to generate query");
449                     return OC_STACK_ERROR;
450                 }
451                 OC_LOG_V(DEBUG, TAG, "Query=%s", query);
452
453                 OCCallbackData cbData;
454                 cbData.cb = &SecurePortDiscoveryHandler;
455                 cbData.context = ctx;
456                 cbData.cd = NULL;
457                 OCStackResult ret = OCDoResource(NULL, OC_REST_DISCOVER, query, 0, 0,
458                         clientResponse->connType, OC_LOW_QOS, &cbData, NULL, 0);
459                 // TODO: Should we use the default secure port in case of error?
460                 if(OC_STACK_OK != ret)
461                 {
462                     OC_LOG(ERROR, TAG, "Failed to Secure Port Discovery");
463                     return OC_STACK_DELETE_TRANSACTION;
464                 }
465                 else
466                 {
467                     OC_LOG_V(INFO, TAG, "OCDoResource with [%s] Success", query);
468                 }
469                 OC_LOG(INFO, TAG, "Exiting ProvisionDiscoveryHandler.");
470             }
471
472             return  OC_STACK_KEEP_TRANSACTION;
473         }
474     }
475     else
476     {
477         OC_LOG(INFO, TAG, "Skiping Null response");
478         return OC_STACK_KEEP_TRANSACTION;
479     }
480
481     return  OC_STACK_DELETE_TRANSACTION;
482 }
483
484 /**
485  * Discover owned/unowned devices in the same IP subnet. .
486  *
487  * @param[in] waittime      Timeout in seconds.
488  * @param[in] isOwned       bool flag for owned / unowned discovery
489  * @param[in] ppDevicesList        List of OCProvisionDev_t.
490  *
491  * @return OC_STACK_OK on success otherwise error.
492  */
493 OCStackResult PMDeviceDiscovery(unsigned short waittime, bool isOwned, OCProvisionDev_t **ppDevicesList)
494 {
495     OC_LOG(DEBUG, TAG, "IN PMDeviceDiscovery");
496
497     if (NULL != *ppDevicesList)
498     {
499         OC_LOG(ERROR, TAG, "List is not null can cause memory leak");
500         return OC_STACK_INVALID_PARAM;
501     }
502
503     const char DOXM_OWNED_FALSE_MULTICAST_QUERY[] = "/oic/sec/doxm?Owned=FALSE";
504     const char DOXM_OWNED_TRUE_MULTICAST_QUERY[] = "/oic/sec/doxm?Owned=TRUE";
505
506     OCCallbackData cbData;
507     cbData.cb = &DeviceDiscoveryHandler;
508     cbData.context = (void *)ppDevicesList;
509     cbData.cd = NULL;
510     OCStackResult res = OC_STACK_ERROR;
511
512     const char* query = isOwned ? DOXM_OWNED_TRUE_MULTICAST_QUERY :
513                                   DOXM_OWNED_FALSE_MULTICAST_QUERY;
514
515     res = OCDoResource(NULL, OC_REST_DISCOVER, query, 0, 0,
516                                      CT_DEFAULT, OC_LOW_QOS, &cbData, NULL, 0);
517     if (res != OC_STACK_OK)
518     {
519         OC_LOG(ERROR, TAG, "OCStack resource error");
520         goto exit;
521     }
522
523     //Waiting for each response.
524     res = PMTimeout(waittime);
525     if(OC_STACK_OK != res)
526     {
527         OC_LOG(ERROR, TAG, "Failed to wait response for secure discovery.");
528         goto exit;
529     }
530
531     OC_LOG(DEBUG, TAG, "OUT PMDeviceDiscovery");
532 exit:
533     return res;
534 }