1 /******************************************************************
3 * Copyright 2016 Samsung Electronics All Rights Reserved.
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 ******************************************************************/
20 ///////////////////////////////////////////////////////////////////////
21 //NOTE : This sample server is generated based on ocserverbasicops.cpp
22 ///////////////////////////////////////////////////////////////////////
23 #include "iotivity_config.h"
35 #include "ocpayload.h"
39 /** @todo stop-gap for naming issue. Windows.h does not like us to use ERROR */
43 #endif //HAVE_WINDOWS_H
44 #include "platform_features.h"
46 #include "pkix_interface.h"
47 #include "hw_emul/hw_interface.h"
48 #include "oxmverifycommon.h"
49 #include "casecurityinterface.h"
51 #define TAG "SAMPLE_MANUFACTURER_CERT"
55 /* Structure to represent a LED resource */
56 typedef struct LEDRESOURCE{
57 OCResourceHandle handle;
62 static LEDResource LED;
63 // This variable determines instance number of the LED resource.
64 // Used by POST method to create a new instance of LED resource.
65 static int gCurrLedInstance = 0;
66 #define SAMPLE_MAX_NUM_POST_INSTANCE 2
67 static LEDResource gLedInstance[SAMPLE_MAX_NUM_POST_INSTANCE];
69 char *gResourceUri= (char *)"/a/led";
71 //Secure Virtual Resource database for Iotivity Server
72 //It contains Server's Identity and the manufacturer certificate
73 static char CRED_FILE[] = "oic_svr_db_server_mfg.dat";
75 /* Function that creates a new LED resource by calling the
76 * OCCreateResource() method.
78 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower);
80 /* This method converts the payload to JSON format */
81 OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest);
83 /* Following methods process the PUT, GET, POST
86 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
87 OCRepPayload **payload);
88 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
89 OCRepPayload **payload);
90 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
91 OCEntityHandlerResponse *response,
92 OCRepPayload **payload);
94 /* Entity Handler callback functions */
96 OCEntityHandlerCb (OCEntityHandlerFlag flag,
97 OCEntityHandlerRequest *entityHandlerRequest,
100 const char *getResult(OCStackResult result) {
103 return "OC_STACK_OK";
104 case OC_STACK_RESOURCE_CREATED:
105 return "OC_STACK_RESOURCE_CREATED";
106 case OC_STACK_RESOURCE_DELETED:
107 return "OC_STACK_RESOURCE_DELETED";
108 case OC_STACK_INVALID_URI:
109 return "OC_STACK_INVALID_URI";
110 case OC_STACK_INVALID_QUERY:
111 return "OC_STACK_INVALID_QUERY";
112 case OC_STACK_INVALID_IP:
113 return "OC_STACK_INVALID_IP";
114 case OC_STACK_INVALID_PORT:
115 return "OC_STACK_INVALID_PORT";
116 case OC_STACK_INVALID_CALLBACK:
117 return "OC_STACK_INVALID_CALLBACK";
118 case OC_STACK_INVALID_METHOD:
119 return "OC_STACK_INVALID_METHOD";
120 case OC_STACK_NO_MEMORY:
121 return "OC_STACK_NO_MEMORY";
122 case OC_STACK_COMM_ERROR:
123 return "OC_STACK_COMM_ERROR";
124 case OC_STACK_INVALID_PARAM:
125 return "OC_STACK_INVALID_PARAM";
126 case OC_STACK_NOTIMPL:
127 return "OC_STACK_NOTIMPL";
128 case OC_STACK_NO_RESOURCE:
129 return "OC_STACK_NO_RESOURCE";
130 case OC_STACK_RESOURCE_ERROR:
131 return "OC_STACK_RESOURCE_ERROR";
132 case OC_STACK_SLOW_RESOURCE:
133 return "OC_STACK_SLOW_RESOURCE";
134 case OC_STACK_NO_OBSERVERS:
135 return "OC_STACK_NO_OBSERVERS";
137 case OC_STACK_PRESENCE_STOPPED:
138 return "OC_STACK_PRESENCE_STOPPED";
141 return "OC_STACK_ERROR";
147 OCRepPayload* getPayload(const char* uri, int64_t power, bool state)
149 OCRepPayload* payload = OCRepPayloadCreate();
152 OIC_LOG(ERROR, TAG, "Failed to allocate Payload");
156 OCRepPayloadSetUri(payload, uri);
157 OCRepPayloadSetPropBool(payload, "state", state);
158 OCRepPayloadSetPropInt(payload, "power", power);
163 //This function takes the request as an input and returns the response
164 OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest)
166 if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
168 OIC_LOG(ERROR, TAG, "Incoming payload not a representation");
172 OCRepPayload* input = (OCRepPayload*)(ehRequest->payload);
174 LEDResource *currLEDResource = &LED;
176 if (ehRequest->resource == gLedInstance[0].handle)
178 currLEDResource = &gLedInstance[0];
179 gResourceUri = (char *) "/a/led/0";
181 else if (ehRequest->resource == gLedInstance[1].handle)
183 currLEDResource = &gLedInstance[1];
184 gResourceUri = (char *) "/a/led/1";
187 if(OC_REST_PUT == ehRequest->method)
189 // Get pointer to query
191 if(OCRepPayloadGetPropInt(input, "power", &pow))
193 currLEDResource->power =pow;
197 if(OCRepPayloadGetPropBool(input, "state", &state))
199 currLEDResource->state = state;
203 return getPayload(gResourceUri, currLEDResource->power, currLEDResource->state);
206 OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
207 OCRepPayload **payload)
209 OCEntityHandlerResult ehResult;
211 OCRepPayload *getResp = constructResponse(ehRequest);
220 ehResult = OC_EH_ERROR;
226 OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
227 OCRepPayload **payload)
229 OCEntityHandlerResult ehResult;
231 OCRepPayload *putResp = constructResponse(ehRequest);
240 ehResult = OC_EH_ERROR;
246 OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
247 OCEntityHandlerResponse *response, OCRepPayload **payload)
249 OCRepPayload *respPLPost_led = NULL;
250 OCEntityHandlerResult ehResult = OC_EH_OK;
253 * The entity handler determines how to process a POST request.
254 * Per the REST paradigm, POST can also be used to update representation of existing
255 * resource or create a new resource.
256 * In the sample below, if the POST is for /a/led then a new instance of the LED
257 * resource is created with default representation (if representation is included in
258 * POST payload it can be used as initial values) as long as the instance is
259 * lesser than max new instance count. Once max instance count is reached, POST on
260 * /a/led updated the representation of /a/led (just like PUT)
263 if (ehRequest->resource == LED.handle)
265 if (gCurrLedInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
267 // Create new LED instance
268 char newLedUri[15] = "/a/led/";
269 int newLedUriLength = strlen(newLedUri);
270 snprintf (newLedUri + newLedUriLength, sizeof(newLedUri)-newLedUriLength, "%d", gCurrLedInstance);
272 respPLPost_led = OCRepPayloadCreate();
273 OCRepPayloadSetUri(respPLPost_led, gResourceUri);
274 OCRepPayloadSetPropString(respPLPost_led, "createduri", newLedUri);
276 if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
278 OIC_LOG (INFO, TAG, "Created new LED instance");
279 gLedInstance[gCurrLedInstance].state = 0;
280 gLedInstance[gCurrLedInstance].power = 0;
282 strncpy ((char *)response->resourceUri, newLedUri, MAX_URI_LENGTH);
283 ehResult = OC_EH_RESOURCE_CREATED;
288 respPLPost_led = constructResponse(ehRequest);
293 for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
295 if (ehRequest->resource == gLedInstance[i].handle)
299 respPLPost_led = constructResponse(ehRequest);
304 respPLPost_led = constructResponse(ehRequest);
310 if (respPLPost_led != NULL)
312 *payload = respPLPost_led;
317 OIC_LOG_V (INFO, TAG, "Payload was NULL");
318 ehResult = OC_EH_ERROR;
324 OCEntityHandlerResult
325 OCEntityHandlerCb (OCEntityHandlerFlag flag,
326 OCEntityHandlerRequest *entityHandlerRequest,
329 OIC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
331 OCEntityHandlerResult ehResult = OC_EH_ERROR;
333 OCEntityHandlerResponse response;
334 memset(&response, 0, sizeof(response));
337 if (!entityHandlerRequest)
339 OIC_LOG (ERROR, TAG, "Invalid request pointer");
343 OCRepPayload* payload = NULL;
345 if (flag & OC_REQUEST_FLAG)
347 OIC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
348 if (entityHandlerRequest)
350 if (OC_REST_GET == entityHandlerRequest->method)
352 OIC_LOG (INFO, TAG, "Received OC_REST_GET from client");
353 ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
355 else if (OC_REST_PUT == entityHandlerRequest->method)
357 OIC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
358 ehResult = ProcessPutRequest (entityHandlerRequest, &payload);
360 else if (OC_REST_POST == entityHandlerRequest->method)
362 OIC_LOG (INFO, TAG, "Received OC_REST_POST from client");
363 ehResult = ProcessPostRequest (entityHandlerRequest, &response, &payload);
367 OIC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
368 entityHandlerRequest->method);
369 ehResult = OC_EH_ERROR;
372 if (ehResult == OC_EH_OK && ehResult != OC_EH_FORBIDDEN)
374 // Format the response. Note this requires some info about the request
375 response.requestHandle = entityHandlerRequest->requestHandle;
376 response.resourceHandle = entityHandlerRequest->resource;
377 response.ehResult = ehResult;
378 response.payload = (OCPayload*)(payload);
379 response.numSendVendorSpecificHeaderOptions = 0;
380 memset(response.sendVendorSpecificHeaderOptions, 0,
381 sizeof(response.sendVendorSpecificHeaderOptions));
382 memset(response.resourceUri, 0, sizeof(response.resourceUri));
383 // Indicate that response is NOT in a persistent buffer
384 response.persistentBufferFlag = 0;
387 if (OCDoResponse(&response) != OC_STACK_OK)
389 OIC_LOG(ERROR, TAG, "Error sending response");
390 ehResult = OC_EH_ERROR;
396 OCPayloadDestroy(response.payload);
400 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
401 void handleSigInt(int signum)
403 if (signum == SIGINT)
409 OCStackResult confirmCB_thread()
415 printf(" > Press 1 for confirmation\n");
416 printf(" > Press 0 otherwise\n");
418 for (int ret=0; 1!=ret; )
420 ret = scanf("%d", &userConfirm);
421 for (; 0x20<=getchar(); ); // for removing overflow garbage
422 // '0x20<=code' is character region
424 if (1 == userConfirm)
426 SendUserConfirm(true);
429 else if (0 == userConfirm)
431 SendUserConfirm(false);
434 printf(" Entered Wrong Number. Please Enter Again\n");
439 OCStackResult confirmCB(void * ctx)
443 pthread_create (&threadId, NULL, &confirmCB_thread, NULL);
447 void confirmNoCertCB(CACertificateVerificationStatus_t status)
449 if (CA_CERTIFICATE_VERIFY_SUCCESS_MUTUAL == status)
451 printf(" > Peer certificate verification successful");
453 else if (CA_CERTIFICATE_VERIFY_NO_CERT == status)
455 printf(" > Peer has not provided certificate\n");
457 else if (CA_CERTIFICATE_VERIFY_FAILED == status)
459 printf(" > Peer certificate verification failed\n");
464 void informOxmSelCB(OicSecOxm_t oxmSel)
\r
466 printf(" > OXM selected: 0x%x\n", oxmSel);
\r
469 FILE* server_fopen(const char *path, const char *mode)
472 return fopen(CRED_FILE, mode);
475 int main(int argc, char **argv)
477 struct timespec timeout;
479 OIC_LOG(DEBUG, TAG, "OCServer is starting...");
482 char cert_file[4096] = {0,};
483 char key_file[4096] = {0,};
484 char key_pass[32] = {0,};
487 while ((opt = getopt(argc, argv, "c:k:p:")) != -1)
492 strncpy(cert_file, optarg, sizeof(cert_file) - 1);
493 printf("Set own certificate file : %s\n", cert_file);
496 strncpy(key_file, optarg, sizeof(key_file) - 1);
497 printf("Set private key file : %s\n", key_file);
500 strncpy(key_pass, optarg, sizeof(key_pass) - 1);
501 printf("Set private key password : %s\n", key_pass);
504 printf("Not set any options\n");
508 // Initialize Persistent Storage for SVR database
509 OCPersistentStorage ps = {server_fopen, fread, fwrite, fclose, unlink, NULL, NULL};
511 SetAsyncUserConfirmCB(NULL, confirmCB);
512 SetInformOxmSelCB(informOxmSelCB);
513 CAsetCertificateVerificationCallback(confirmNoCertCB);
515 OCRegisterPersistentStorageHandler(&ps);
517 if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
519 OIC_LOG(ERROR, TAG, "OCStack init error");
523 // Register HW secure storage callback
524 if (0 < strlen(cert_file) && 0 < strlen(key_file))
526 if (0 == SSemulSetCertkeyFilepath(cert_file, key_file, key_pass))
528 if (0 != SetHwPkixCallbacks(HWGetKeyContext,
530 HWGetOwnCertificateChain,
533 printf("Fail to regist HW Pkix Callbacks");
538 printf("Fail to set cert/key file path");
543 printf("\n [ Not set any mfg cert options ]\n");
544 printf(" Possible options: %s [-c certificate file path]"
545 " [-k key file path] [-p key password]\n\n", argv[0]);
549 * Declare and create the example resource: LED
551 createLEDResource(gResourceUri, &LED, false, 0);
554 timeout.tv_nsec = 100000000L;
556 // Break from loop with Ctrl-C
557 OIC_LOG(INFO, TAG, "Entering ocserver main loop...");
558 signal(SIGINT, handleSigInt);
561 if (OCProcess() != OC_STACK_OK)
563 OIC_LOG(ERROR, TAG, "OCStack process error");
566 nanosleep(&timeout, NULL);
569 OIC_LOG(INFO, TAG, "Exiting ocserver main loop...");
571 if (OCStop() != OC_STACK_OK)
573 OIC_LOG(ERROR, TAG, "OCStack process error");
579 int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower)
583 OIC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
587 ledResource->state = resourceState;
588 ledResource->power= resourcePower;
589 OCStackResult res = OCCreateResource(&(ledResource->handle),
591 OC_RSRVD_INTERFACE_DEFAULT,
595 OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE);
596 OIC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));