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