Implementation of Things Manager feature.
[platform/upstream/iotivity.git] / resource / src / InProcServerWrapper.cpp
1 //******************************************************************
2 //
3 // Copyright 2014 Intel Mobile Communications GmbH 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
21 #include <random>
22 #include <cstring>
23 #include <cstdlib>
24 #include <iostream>
25 #include <algorithm>
26 #include <map>
27 #include <sstream>
28 #include <string>
29
30 #include <InProcServerWrapper.h>
31 #include <InitializeException.h>
32 #include <OCResourceRequest.h>
33 #include <OCResourceResponse.h>
34 #include <ocstack.h>
35 #include <OCApi.h>
36 #include <OCPlatform.h>
37 #include <OCUtilities.h>
38
39 using namespace std;
40 using namespace OC;
41
42 std::map <OCResourceHandle, OC::EntityHandler>  entityHandlerMap;
43 std::map <OCResourceHandle, std::string> resourceUriMap;
44 EntityHandler defaultDeviceEntityHandler = 0;
45
46 void formResourceRequest(OCEntityHandlerFlag flag,
47                          OCEntityHandlerRequest * entityHandlerRequest,
48                          std::shared_ptr<OCResourceRequest> pRequest)
49 {
50     pRequest->setRequestHandle(entityHandlerRequest->requestHandle);
51     pRequest->setResourceHandle(entityHandlerRequest->resource);
52
53     if(flag & OC_INIT_FLAG)
54     {
55         pRequest->setRequestHandlerFlag(OC::RequestHandlerFlag::InitFlag);
56     }
57
58     if(flag & OC_REQUEST_FLAG)
59     {
60         pRequest->setRequestHandlerFlag(OC::RequestHandlerFlag::RequestFlag);
61
62         if(entityHandlerRequest)
63         {
64             if(entityHandlerRequest->query)
65             {
66                 std::string querystr(reinterpret_cast<char*>(entityHandlerRequest->query));
67
68                 OC::Utilities::QueryParamsKeyVal qp = OC::Utilities::getQueryParams(querystr);
69
70                 if(qp.size() > 0)
71                 {
72                     pRequest->setQueryParams(qp);
73                 }
74             }
75             if(entityHandlerRequest->numRcvdVendorSpecificHeaderOptions != 0)
76             {
77                 //Set the header options here.
78                 uint16_t optionID;
79                 std::string optionData;
80                 HeaderOptions headerOptions;
81
82                 for(int i = 0;
83                     i < entityHandlerRequest->numRcvdVendorSpecificHeaderOptions;
84                     i++)
85                 {
86                     optionID = entityHandlerRequest->rcvdVendorSpecificHeaderOptions[i].optionID;
87                     optionData = reinterpret_cast<const char*>
88                              (entityHandlerRequest->rcvdVendorSpecificHeaderOptions[i].optionData);
89                     HeaderOption::OCHeaderOption headerOption(optionID, optionData);
90                     headerOptions.push_back(headerOption);
91                 }
92                 pRequest->setHeaderOptions(headerOptions);
93             }
94
95             if(OC_REST_GET == entityHandlerRequest->method)
96             {
97                 pRequest->setRequestType(OC::PlatformCommands::GET);
98             }
99             else if(OC_REST_PUT == entityHandlerRequest->method)
100             {
101                 pRequest->setRequestType(OC::PlatformCommands::PUT);
102                 pRequest->setPayload(std::string(reinterpret_cast<const char*>
103                                             (entityHandlerRequest->reqJSONPayload)));
104             }
105             else if(OC_REST_POST == entityHandlerRequest->method)
106             {
107                 pRequest->setRequestType(OC::PlatformCommands::POST);
108                 pRequest->setPayload(std::string(reinterpret_cast<const char*>
109                                             (entityHandlerRequest->reqJSONPayload)));
110             }
111             else if(OC_REST_DELETE == entityHandlerRequest->method)
112             {
113                 pRequest->setRequestType(OC::PlatformCommands::DELETE);
114             }
115         }
116     }
117
118     if(flag & OC_OBSERVE_FLAG)
119     {
120         pRequest->setRequestHandlerFlag(
121                    OC::RequestHandlerFlag::RequestFlag | OC::RequestHandlerFlag::ObserverFlag);
122
123         if(entityHandlerRequest)
124         {
125             OC::ObservationInfo observationInfo;
126             observationInfo.action = (OC::ObserveAction) entityHandlerRequest->obsInfo.action;
127             observationInfo.obsId = entityHandlerRequest->obsInfo.obsId;
128             pRequest->setObservationInfo(observationInfo);
129         }
130     }
131 }
132
133 OCEntityHandlerResult DefaultEntityHandlerWrapper(OCEntityHandlerFlag flag,
134                                                   OCEntityHandlerRequest * entityHandlerRequest,
135                                                   char* uri)
136 {
137     OCEntityHandlerResult result = OC_EH_ERROR;
138
139     OC::oclog() << "In Default device entity handler wrapper";
140
141     if(NULL == entityHandlerRequest)
142     {
143         oclog() << "Entity handler request is NULL.";
144         return OC_EH_ERROR;
145     }
146
147     auto pRequest = std::make_shared<OC::OCResourceRequest>();
148
149     formResourceRequest(flag, entityHandlerRequest, pRequest);
150
151     pRequest->setResourceUri(std::string(uri));
152
153     if(defaultDeviceEntityHandler)
154     {
155         result = defaultDeviceEntityHandler(pRequest);
156     }
157     else
158     {
159         oclog() << "Default device entity handler was not set.";
160         return OC_EH_ERROR;
161     }
162
163     return result;
164 }
165
166
167 OCEntityHandlerResult EntityHandlerWrapper(OCEntityHandlerFlag flag,
168                                            OCEntityHandlerRequest * entityHandlerRequest)
169 {
170     OCEntityHandlerResult result = OC_EH_ERROR;
171
172     oclog() << "\nIn entity handler wrapper: " << endl;
173
174     if(NULL == entityHandlerRequest)
175     {
176         oclog() << "Entity handler request is NULL."  << endl;
177         return OC_EH_ERROR;
178     }
179
180     auto pRequest = std::make_shared<OC::OCResourceRequest>();
181
182     formResourceRequest(flag, entityHandlerRequest, pRequest);
183
184     // Finding the corresponding URI for a resource handle and set the URI in the request
185     auto resourceUriEntry = resourceUriMap.find(entityHandlerRequest->resource);
186     if(resourceUriEntry != resourceUriMap.end())
187     {
188         pRequest->setResourceUri(resourceUriEntry->second);
189     }
190     else
191     {
192         oclog() << "Resource handle not found; Resource URI not set in request";
193         return OC_EH_ERROR;
194     }
195
196     // Finding the corresponding CPP Application entityHandler for a given resource
197     auto entityHandlerEntry = entityHandlerMap.find(entityHandlerRequest->resource);
198
199     if(entityHandlerEntry != entityHandlerMap.end())
200     {
201         // Call CPP Application Entity Handler
202         if(entityHandlerEntry->second)
203         {
204             result = entityHandlerEntry->second(pRequest);
205         }
206         else
207         {
208             oclog() << "C stack should not call again for parent resource\n";
209             return OC_EH_ERROR;
210         }
211     }
212     else
213     {
214         oclog() << "No entity handler found."  << endl;
215         return OC_EH_ERROR;
216     }
217
218     return result;
219 }
220
221 namespace OC
222 {
223     InProcServerWrapper::InProcServerWrapper(
224         std::weak_ptr<std::recursive_mutex> csdkLock, PlatformConfig cfg)
225      : m_csdkLock(csdkLock)
226     {
227         OCMode initType;
228
229         if(cfg.mode == ModeType::Server)
230         {
231             initType = OC_SERVER;
232         }
233         else if (cfg.mode == ModeType::Both)
234         {
235             initType = OC_CLIENT_SERVER;
236         }
237         else
238         {
239             throw InitializeException(OC::InitException::NOT_CONFIGURED_AS_SERVER,
240                                       OC_STACK_INVALID_PARAM);
241         }
242
243         OCStackResult result = OCInit(cfg.ipAddress.c_str(), cfg.port, initType);
244
245         if(OC_STACK_OK != result)
246         {
247             throw InitializeException(OC::InitException::STACK_INIT_ERROR, result);
248         }
249
250         m_threadRun = true;
251         m_processThread = std::thread(&InProcServerWrapper::processFunc, this);
252     }
253
254     void InProcServerWrapper::processFunc()
255     {
256         auto cLock = m_csdkLock.lock();
257         while(cLock && m_threadRun)
258         {
259             OCStackResult result;
260
261             {
262                 std::lock_guard<std::recursive_mutex> lock(*cLock);
263                 result = OCProcess();
264             }
265
266             // ...the value of variable result is simply ignored for now.
267             if(OC_STACK_ERROR == result)
268              ;
269
270             std::this_thread::sleep_for(std::chrono::milliseconds(10));
271         }
272     }
273
274     OCStackResult InProcServerWrapper::registerResource(
275                     OCResourceHandle& resourceHandle,
276                     std::string& resourceURI,
277                     const std::string& resourceTypeName,
278                     const std::string& resourceInterface,
279                     EntityHandler& eHandler,
280                     uint8_t resourceProperties)
281
282     {
283         OCStackResult result = OC_STACK_ERROR;
284
285         auto cLock = m_csdkLock.lock();
286
287         if(cLock)
288         {
289             std::lock_guard<std::recursive_mutex> lock(*cLock);
290
291             if(NULL != eHandler)
292             {
293                 result = OCCreateResource(&resourceHandle, // OCResourceHandle *handle
294                             resourceTypeName.c_str(), // const char * resourceTypeName
295                             resourceInterface.c_str(), //const char * resourceInterfaceName //TODO fix this
296                             resourceURI.c_str(), // const char * uri
297                             EntityHandlerWrapper, // OCEntityHandler entityHandler
298                             resourceProperties // uint8_t resourceProperties
299                             );
300             }
301             else
302             {
303                 result = OCCreateResource(&resourceHandle, // OCResourceHandle *handle
304                             resourceTypeName.c_str(), // const char * resourceTypeName
305                             resourceInterface.c_str(), //const char * resourceInterfaceName //TODO fix this
306                             resourceURI.c_str(), // const char * uri
307                             NULL, // OCEntityHandler entityHandler
308                             resourceProperties // uint8_t resourceProperties
309                             );
310             }
311
312             if(result != OC_STACK_OK)
313             {
314                 resourceHandle = (OCResourceHandle) 0;
315             }
316             else
317             {
318                 entityHandlerMap[resourceHandle] = eHandler;
319                 resourceUriMap[resourceHandle] = resourceURI;
320             }
321         }
322         else
323         {
324             result = OC_STACK_ERROR;
325         }
326
327         return result;
328     }
329
330     OCStackResult InProcServerWrapper::registerResourceWithHost(
331                     OCResourceHandle& resourceHandle,
332                     std::string& resourceHOST,
333                     std::string& resourceURI,
334                     const std::string& resourceTypeName,
335                     const std::string& resourceInterface,
336                     EntityHandler& eHandler,
337                     uint8_t resourceProperties)
338
339     {
340         OCStackResult result = OC_STACK_ERROR;
341
342         auto cLock = m_csdkLock.lock();
343
344         if (cLock)
345         {
346             std::lock_guard < std::recursive_mutex > lock(*cLock);
347
348             if (NULL != eHandler)
349             {
350                 result = OCCreateResourceWithHost(&resourceHandle, // OCResourceHandle *handle
351                         resourceTypeName.c_str(), // const char * resourceTypeName
352                         resourceInterface.c_str(), //const char * resourceInterfaceName //TODO fix
353                         resourceHOST.c_str(), // const char * host
354                         (resourceHOST + resourceURI).c_str(), // const char * uri
355                         EntityHandlerWrapper, // OCEntityHandler entityHandler
356                         resourceProperties // uint8_t resourceProperties
357                         );
358             }
359             else
360             {
361                 result = OCCreateResourceWithHost(&resourceHandle, // OCResourceHandle *handle
362                         resourceTypeName.c_str(), // const char * resourceTypeName
363                         resourceInterface.c_str(), //const char * resourceInterfaceName //TODO fix
364                         resourceHOST.c_str(), // const char * host
365                         (resourceHOST + resourceURI).c_str(), // const char * uri
366                         nullptr, // OCEntityHandler entityHandler
367                         resourceProperties // uint8_t resourceProperties
368                         );
369             }
370
371             if (result != OC_STACK_OK)
372             {
373                 resourceHandle = nullptr;
374             }
375             else
376             {
377                 entityHandlerMap[resourceHandle] = eHandler;
378                 resourceUriMap[resourceHandle] = resourceURI;
379             }
380         }
381         else
382         {
383             result = OC_STACK_ERROR;
384         }
385
386         return result;
387     }
388
389     OCStackResult InProcServerWrapper::setDefaultDeviceEntityHandler
390                                         (EntityHandler entityHandler)
391     {
392         OCStackResult result = OC_STACK_ERROR;
393
394         defaultDeviceEntityHandler = entityHandler;
395
396         if(entityHandler)
397         {
398             result = OCSetDefaultDeviceEntityHandler(DefaultEntityHandlerWrapper);
399         }
400         else
401         {
402             // If Null passed we unset
403             result = OCSetDefaultDeviceEntityHandler(NULL);
404         }
405
406         return result;
407     }
408
409     OCStackResult InProcServerWrapper::unregisterResource(const OCResourceHandle& resourceHandle)
410     {
411         auto cLock = m_csdkLock.lock();
412         OCStackResult result = OC_STACK_ERROR;
413
414         if(cLock)
415         {
416             std::lock_guard<std::recursive_mutex> lock(*cLock);
417             result = OCDeleteResource(resourceHandle);
418
419             if(result == OC_STACK_OK)
420             {
421                 resourceUriMap.erase(resourceHandle);
422             }
423             else
424             {
425                 throw OCException(OC::Exception::RESOURCE_UNREG_FAILED, result);
426             }
427         }
428         else
429         {
430             result = OC_STACK_ERROR;
431         }
432
433         return result;
434     }
435
436     OCStackResult InProcServerWrapper::bindTypeToResource(const OCResourceHandle& resourceHandle,
437                      const std::string& resourceTypeName)
438     {
439         auto cLock = m_csdkLock.lock();
440         OCStackResult result;
441         if(cLock)
442         {
443             std::lock_guard<std::recursive_mutex> lock(*cLock);
444             result = OCBindResourceTypeToResource(resourceHandle, resourceTypeName.c_str());
445         }
446         else
447         {
448             result = OC_STACK_ERROR;
449         }
450
451         if (result != OC_STACK_OK)
452         {
453             throw OCException(OC::Exception::BIND_TYPE_FAILED, result);
454         }
455         return result;
456     }
457
458     OCStackResult InProcServerWrapper::bindInterfaceToResource(
459                      const OCResourceHandle& resourceHandle,
460                      const std::string& resourceInterfaceName)
461     {
462         auto cLock = m_csdkLock.lock();
463         OCStackResult result;
464         if(cLock)
465         {
466             std::lock_guard<std::recursive_mutex> lock(*cLock);
467             result = OCBindResourceInterfaceToResource(resourceHandle,
468                         resourceInterfaceName.c_str());
469         }
470         else
471         {
472             result = OC_STACK_ERROR;
473         }
474
475         if (result != OC_STACK_OK)
476         {
477             throw OCException(OC::Exception::BIND_INTERFACE_FAILED, result);
478         }
479         return result;
480     }
481
482     OCStackResult InProcServerWrapper::startPresence(const unsigned int seconds)
483     {
484         auto cLock = m_csdkLock.lock();
485         OCStackResult result = OC_STACK_ERROR;
486         if(cLock)
487         {
488             std::lock_guard<std::recursive_mutex> lock(*cLock);
489             result = OCStartPresence(seconds);
490         }
491
492         if(result != OC_STACK_OK)
493         {
494             throw OCException(OC::Exception::START_PRESENCE_FAILED, result);
495         }
496         return result;
497     }
498
499     OCStackResult InProcServerWrapper::stopPresence()
500     {
501         auto cLock = m_csdkLock.lock();
502         OCStackResult result = OC_STACK_ERROR;
503         if(cLock)
504         {
505             std::lock_guard<std::recursive_mutex> lock(*cLock);
506             result = OCStopPresence();
507         }
508
509         if(result != OC_STACK_OK)
510         {
511             throw OCException(OC::Exception::END_PRESENCE_FAILED, result);
512         }
513         return result;
514     }
515
516     OCStackResult InProcServerWrapper::sendResponse(
517         const std::shared_ptr<OCResourceResponse> pResponse)
518     {
519         auto cLock = m_csdkLock.lock();
520         OCStackResult result = OC_STACK_ERROR;
521
522         if(!pResponse)
523         {
524             result = OC_STACK_MALFORMED_RESPONSE;
525             throw OCException(OC::Exception::STR_NULL_RESPONSE, OC_STACK_MALFORMED_RESPONSE);
526         }
527         else
528         {
529             OCEntityHandlerResponse response;
530             std::string payLoad;
531             HeaderOptions serverHeaderOptions;
532
533             payLoad = pResponse->getPayload();
534             serverHeaderOptions = pResponse->getHeaderOptions();
535
536             response.requestHandle = pResponse->getRequestHandle();
537             response.resourceHandle = pResponse->getResourceHandle();
538             response.ehResult = pResponse->getResponseResult();
539             response.payload = (unsigned char*) payLoad.c_str();
540             response.payloadSize = payLoad.length() + 1;
541             response.persistentBufferFlag = 0;
542
543             response.numSendVendorSpecificHeaderOptions = serverHeaderOptions.size();
544             int i = 0;
545             for (auto it=serverHeaderOptions.begin(); it != serverHeaderOptions.end(); ++it)
546             {
547                 response.sendVendorSpecificHeaderOptions[i].protocolID = OC_COAP_ID;
548                 response.sendVendorSpecificHeaderOptions[i].optionID =
549                     static_cast<uint16_t>(it->getOptionID());
550                 response.sendVendorSpecificHeaderOptions[i].optionLength =
551                     (it->getOptionData()).length() + 1;
552                 memcpy(response.sendVendorSpecificHeaderOptions[i].optionData,
553                     (it->getOptionData()).c_str(),
554                     (it->getOptionData()).length() + 1);
555                 i++;
556             }
557
558             if(OC_EH_RESOURCE_CREATED == response.ehResult)
559             {
560                 std::string createdUri = pResponse->getNewResourceUri();
561                 strncpy(reinterpret_cast<char*>(response.resourceUri),
562                         createdUri.c_str(),
563                         createdUri.length() + 1);
564             }
565
566             if(cLock)
567             {
568                 std::lock_guard<std::recursive_mutex> lock(*cLock);
569                 result = OCDoResponse(&response);
570             }
571             else
572             {
573                 result = OC_STACK_ERROR;
574             }
575
576             if(result != OC_STACK_OK)
577             {
578                 oclog() << "Error sending response\n";
579             }
580             return result;
581         }
582     }
583
584     InProcServerWrapper::~InProcServerWrapper()
585     {
586         if(m_processThread.joinable())
587         {
588             m_threadRun = false;
589             m_processThread.join();
590         }
591
592         OCStop();
593     }
594 }