svace fix
[platform/upstream/iotivity.git] / resource / csdk / security / provisioning / src / ownershiptransfermanager.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
21 // Defining _POSIX_C_SOURCE macro with 199309L (or greater) as value
22 // causes header files to expose definitions
23 // corresponding to the POSIX.1b, Real-time extensions
24 // (IEEE Std 1003.1b-1993) specification
25 //
26 // For this specific file, see use of clock_gettime,
27 // Refer to http://pubs.opengroup.org/stage7tc1/functions/clock_gettime.html
28 // and to http://man7.org/linux/man-pages/man2/clock_gettime.2.html
29 #ifndef _POSIX_C_SOURCE
30 #define _POSIX_C_SOURCE 200809L
31 #endif
32
33 #include "iotivity_config.h"
34 #ifdef HAVE_TIME_H
35 #include <time.h>
36 #endif
37 #ifdef HAVE_UNISTD_H
38 #include <unistd.h>
39 #endif
40 #ifdef HAVE_SYS_TIME_H
41 #include <sys/time.h>
42 #endif
43 #include <stdbool.h>
44 #include <string.h>
45
46 #include "logger.h"
47 #include "oic_malloc.h"
48 #include "oic_string.h"
49 #include "cacommon.h"
50 #include "cainterface.h"
51 #include "base64.h"
52 #include "cJSON.h"
53 #include "global.h"
54
55 #include "srmresourcestrings.h"
56 #include "doxmresource.h"
57 #include "pstatresource.h"
58 #include "credresource.h"
59 #include "aclresource.h"
60 #include "ownershiptransfermanager.h"
61 #include "securevirtualresourcetypes.h"
62 #include "oxmjustworks.h"
63 #include "pmtypes.h"
64 #include "pmutility.h"
65 #include "srmutility.h"
66 #include "provisioningdatabasemanager.h"
67 #include "oxmrandompin.h"
68 #include "ocpayload.h"
69 #include "payload_logging.h"
70
71 #define TAG "OTM"
72
73 /**
74  * Array to store the callbacks for each owner transfer method.
75  */
76 static OTMCallbackData_t g_OTMDatas[OIC_OXM_COUNT];
77
78 /**
79  * Variables for pointing the OTMContext to be used in the DTLS handshake result callback.
80  */
81 static OTMContext_t* g_otmCtx = NULL;
82
83 /**
84  * Function to select appropriate  provisioning method.
85  *
86  * @param[in] supportedMethods   Array of supported methods
87  * @param[in] numberOfMethods   number of supported methods
88  * @param[out]  selectedMethod         Selected methods
89  * @return  OC_STACK_OK on success
90  */
91 static OCStackResult SelectProvisioningMethod(const OicSecOxm_t *supportedMethods,
92         size_t numberOfMethods, OicSecOxm_t *selectedMethod)
93 {
94     OIC_LOG(DEBUG, TAG, "IN SelectProvisioningMethod");
95
96     if(numberOfMethods == 0 || !supportedMethods)
97     {
98         OIC_LOG(WARNING, TAG, "Could not find a supported OxM.");
99         return OC_STACK_ERROR;
100     }
101
102     *selectedMethod  = supportedMethods[0];
103     for(size_t i = 0; i < numberOfMethods; i++)
104     {
105         if(*selectedMethod < supportedMethods[i])
106         {
107             *selectedMethod =  supportedMethods[i];
108         }
109     }
110
111     return OC_STACK_OK;
112 }
113
114 /**
115  * Function to select operation mode.This function will return most secure common operation mode.
116  *
117  * @param[in] selectedDeviceInfo   selected device information to performing provisioning.
118  * @param[out]   selectedMode   selected operation mode
119  * @return  OC_STACK_OK on success
120  */
121 static void SelectOperationMode(const OCProvisionDev_t *selectedDeviceInfo,
122                                 OicSecDpom_t *selectedMode)
123 {
124     OIC_LOG(DEBUG, TAG, "IN SelectOperationMode");
125     *selectedMode = selectedDeviceInfo->pstat->sm[0];
126     OIC_LOG_V(DEBUG, TAG, "Selected Operation Mode = %d", *selectedMode);
127 }
128
129 /**
130  * Function to start ownership transfer.
131  * This function will send the first request for provisioning,
132  * The next request message is sent from the response handler for this request.
133  *
134  * @param[in] ctx   context value passed to callback from calling function.
135  * @param[in] selectedDevice   selected device information to performing provisioning.
136  * @return  OC_STACK_OK on success
137  */
138 static OCStackResult StartOwnershipTransfer(void* ctx, OCProvisionDev_t* selectedDevice);
139
140 /**
141  * Function to update owner transfer mode
142  *
143  * @param[in]  otmCtx  Context value of ownership transfer.
144  * @return  OC_STACK_OK on success
145  */
146 static OCStackResult PostOwnerTransferModeToResource(OTMContext_t* otmCtx);
147
148 /**
149  * Function to send request to resource to get its pstat resource information.
150  *
151  * @param[in]  otmCtx  Context value of ownership transfer.
152  * @return  OC_STACK_OK on success
153  */
154 static OCStackResult GetProvisioningStatusResource(OTMContext_t* otmCtx);
155
156
157 /**
158  * Function to send  uuid of owner device to new device.
159  * This function would update 'owner of doxm' as UUID for provisioning tool.
160  *
161  * @param[in]  otmCtx  Context value of ownership transfer.
162  * @return  OC_STACK_OK on success
163  */
164 static OCStackResult PostOwnerUuid(OTMContext_t* otmCtx);
165
166 /**
167  * Function to update the operation mode. As per the spec. Operation mode in client driven
168  * single service provisioning it will be updated to 0x3
169  *
170  * @param[in]  otmCtx  Context value of ownership transfer.
171  * @return  OC_STACK_OK on success
172  */
173 static OCStackResult PostUpdateOperationMode(OTMContext_t* otmCtx);
174
175 /**
176  * Function to update the owner credential to new device
177  *
178  * @param[in]  otmCtx  Context value of ownership transfer.
179  * @param[in] selectedOperationMode selected operation mode
180  * @return  OC_STACK_OK on success
181  */
182 static OCStackResult PostOwnerCredential(OTMContext_t* otmCtx);
183
184 /**
185  * Function to send ownerShip info.
186  * This function would update 'owned of doxm' as true.
187  *
188  * @param[in]  otmCtx  Context value of ownership transfer.
189  * @return  OC_STACK_OK on success
190  */
191 static OCStackResult PostOwnershipInformation(OTMContext_t* otmCtx);
192
193 /**
194  * Function to update pstat as Ready for provisioning.
195  * This function would update 'cm' from bx0000,0010 to bx0000,0000.
196  *
197  * @param[in] ctx   context value passed to callback from calling function.
198  * @param[in] selectedDevice   selected device information to performing provisioning.
199  * @return  OC_STACK_OK on success
200  */
201 static OCStackResult PostProvisioningStatus(OTMContext_t* otmCtx);
202
203 /**
204  * Function to update pstat as Ready for Normal Operation.
205  * This function would update 'isop' from false to true.
206  *
207  * @param[in] ctx   context value passed to callback from calling function.
208  * @param[in] selectedDevice   selected device information to performing provisioning.
209  * @return  OC_STACK_OK on success
210  */
211 static OCStackResult PostNormalOperationStatus(OTMContext_t* otmCtx);
212
213 static bool IsComplete(OTMContext_t* otmCtx)
214 {
215     for(size_t i = 0; i < otmCtx->ctxResultArraySize; i++)
216     {
217         if(OC_STACK_CONTINUE == otmCtx->ctxResultArray[i].res)
218         {
219             return false;
220         }
221     }
222
223     return true;
224 }
225
226 /**
227  * Function to save the result of provisioning.
228  *
229  * @param[in,out] otmCtx   Context value of ownership transfer.
230  * @param[in] res   result of provisioning
231  */
232 static void SetResult(OTMContext_t* otmCtx, const OCStackResult res)
233 {
234     OIC_LOG_V(DEBUG, TAG, "IN SetResult : %d ", res);
235
236     if(!otmCtx)
237     {
238         OIC_LOG(WARNING, TAG, "OTMContext is NULL");
239         return;
240     }
241
242     if(otmCtx->selectedDeviceInfo)
243     {
244         //Revert psk_info callback and new deivce uuid in case of random PIN OxM
245         if(OIC_RANDOM_DEVICE_PIN == otmCtx->selectedDeviceInfo->doxm->oxmSel)
246         {
247             if(CA_ADAPTER_IP == ((CAEndpoint_t*)(&otmCtx->selectedDeviceInfo->endpoint))->adapter)
248             {
249                 if(CA_STATUS_OK != CARegisterDTLSCredentialsHandler(GetDtlsPskCredentials))
250                 {
251                     OIC_LOG(WARNING, TAG, "Failed to register DTLS handshake callback.");
252                 }
253             }
254 #ifdef __WITH_TLS__
255             else
256             {
257                 if(CA_STATUS_OK != CAregisterTlsCredentialsHandler(GetDtlsPskCredentials))
258                 {
259                     OIC_LOG(WARNING, TAG, "Failed to register TLS handshake callback.");
260                 }
261             }
262 #endif
263             OicUuid_t emptyUuid = { .id={0}};
264             SetUuidForRandomPinOxm(&emptyUuid);
265         }
266
267         for(size_t i = 0; i < otmCtx->ctxResultArraySize; i++)
268         {
269             if(memcmp(otmCtx->selectedDeviceInfo->doxm->deviceID.id,
270                       otmCtx->ctxResultArray[i].deviceId.id, UUID_LENGTH) == 0)
271             {
272                 otmCtx->ctxResultArray[i].res = res;
273                 if(OC_STACK_OK != res)
274                 {
275                     otmCtx->ctxHasError = true;
276                 }
277             }
278         }
279
280         g_otmCtx = NULL;
281
282         //If all request is completed, invoke the user callback.
283         if(IsComplete(otmCtx))
284         {
285             otmCtx->ctxResultCallback(otmCtx->userCtx, otmCtx->ctxResultArraySize,
286                                        otmCtx->ctxResultArray, otmCtx->ctxHasError);
287             OICFree(otmCtx->ctxResultArray);
288             OICFree(otmCtx);
289         }
290         else
291         {
292             if(OC_STACK_OK != StartOwnershipTransfer(otmCtx,
293                                                      otmCtx->selectedDeviceInfo->next))
294             {
295                 OIC_LOG(ERROR, TAG, "Failed to StartOwnershipTransfer");
296             }
297         }
298     }
299
300     OIC_LOG(DEBUG, TAG, "OUT SetResult");
301 }
302
303 /**
304  * Function to handle the handshake result in OTM.
305  * This function will be invoked after DTLS handshake
306  * @param   endPoint  [IN] The remote endpoint.
307  * @param   errorInfo [IN] Error information from the endpoint.
308  * @return  NONE
309  */
310 void DTLSHandshakeCB(const CAEndpoint_t *endpoint, const CAErrorInfo_t *info)
311 {
312     if(NULL != g_otmCtx && NULL != g_otmCtx->selectedDeviceInfo &&
313        NULL != endpoint && NULL != info)
314     {
315         OIC_LOG_V(INFO, TAG, "Received status from remote device(%s:%d) : %d",
316                  endpoint->addr, endpoint->port, info->result);
317
318         OicSecDoxm_t* newDevDoxm = g_otmCtx->selectedDeviceInfo->doxm;
319
320         if(NULL != newDevDoxm)
321         {
322             OicUuid_t emptyUuid = {.id={0}};
323
324             //Make sure the address matches.
325             if(strncmp(g_otmCtx->selectedDeviceInfo->endpoint.addr,
326                endpoint->addr,
327                sizeof(endpoint->addr)) == 0 &&
328                g_otmCtx->selectedDeviceInfo->securePort == endpoint->port)
329             {
330                 OCStackResult res = OC_STACK_ERROR;
331
332                 //If temporal secure sesstion established successfully
333                 if(CA_STATUS_OK == info->result &&
334                    false == newDevDoxm->owned &&
335                    memcmp(&(newDevDoxm->owner), &emptyUuid, sizeof(OicUuid_t)) == 0)
336                 {
337                     //Send request : POST /oic/sec/doxm [{... , "devowner":"PT's UUID"}]
338                     res = PostOwnerUuid(g_otmCtx);
339                     if(OC_STACK_OK != res)
340                     {
341                         OIC_LOG(ERROR, TAG, "OperationModeUpdate : Failed to send owner information");
342                         SetResult(g_otmCtx, res);
343                     }
344                 }
345                 //In case of authentication failure
346                 else if(CA_DTLS_AUTHENTICATION_FAILURE == info->result)
347                 {
348                     //in case of error from owner credential
349                     if(memcmp(&(newDevDoxm->owner), &emptyUuid, sizeof(OicUuid_t)) != 0 &&
350                         true == newDevDoxm->owned)
351                     {
352                         OIC_LOG(ERROR, TAG, "The owner credential may incorrect.");
353
354                         if(OC_STACK_OK != RemoveCredential(&(newDevDoxm->deviceID)))
355                         {
356                             OIC_LOG(WARNING, TAG, "Failed to remove the invaild owner credential");
357                         }
358                         SetResult(g_otmCtx, OC_STACK_AUTHENTICATION_FAILURE);
359                     }
360                     //in case of error from wrong PIN, re-start the ownership transfer
361                     else if(OIC_RANDOM_DEVICE_PIN == newDevDoxm->oxmSel)
362                     {
363                         OIC_LOG(ERROR, TAG, "The PIN number may incorrect.");
364
365                         memcpy(&(newDevDoxm->owner), &emptyUuid, sizeof(OicUuid_t));
366                         newDevDoxm->owned = false;
367                         g_otmCtx->attemptCnt++;
368
369                         if(WRONG_PIN_MAX_ATTEMP > g_otmCtx->attemptCnt)
370                         {
371                             res = StartOwnershipTransfer(g_otmCtx, g_otmCtx->selectedDeviceInfo);
372                             if(OC_STACK_OK != res)
373                             {
374                                 SetResult(g_otmCtx, res);
375                                 OIC_LOG(ERROR, TAG, "Failed to Re-StartOwnershipTransfer");
376                             }
377                         }
378                         else
379                         {
380                             OIC_LOG(ERROR, TAG, "User has exceeded the number of authentication attempts.");
381                             SetResult(g_otmCtx, OC_STACK_AUTHENTICATION_FAILURE);
382                         }
383                     }
384                     else
385                     {
386                         OIC_LOG(ERROR, TAG, "Failed to establish secure session.");
387                         SetResult(g_otmCtx, OC_STACK_AUTHENTICATION_FAILURE);
388                     }
389                 }
390             }
391         }
392     }
393 }
394
395 /**
396  * Function to save ownerPSK at provisioning tool end.
397  *
398  * @param[in] selectedDeviceInfo   selected device information to performing provisioning.
399  * @return  OC_STACK_OK on success
400  */
401 static OCStackResult SaveOwnerPSK(OCProvisionDev_t *selectedDeviceInfo)
402 {
403     OIC_LOG(DEBUG, TAG, "IN SaveOwnerPSK");
404
405     OCStackResult res = OC_STACK_ERROR;
406
407     CAEndpoint_t endpoint;
408     memset(&endpoint, 0x00, sizeof(CAEndpoint_t));
409     OICStrcpy(endpoint.addr, MAX_ADDR_STR_SIZE_CA, selectedDeviceInfo->endpoint.addr);
410     endpoint.addr[MAX_ADDR_STR_SIZE_CA - 1] = '\0';
411     endpoint.port = selectedDeviceInfo->securePort;
412     endpoint.adapter = selectedDeviceInfo->endpoint.adapter;
413
414     OicUuid_t ptDeviceID = {.id={0}};
415     if (OC_STACK_OK != GetDoxmDeviceID(&ptDeviceID))
416     {
417         OIC_LOG(ERROR, TAG, "Error while retrieving provisioning tool's device ID");
418         return res;
419     }
420
421     uint8_t ownerPSK[OWNER_PSK_LENGTH_128] = {0};
422     OicSecKey_t ownerKey = {ownerPSK, OWNER_PSK_LENGTH_128, OIC_ENCODING_UNKNOW};
423
424     //Generating OwnerPSK
425     CAResult_t pskRet = CAGenerateOwnerPSK(&endpoint,
426             (uint8_t *)GetOxmString(selectedDeviceInfo->doxm->oxmSel),
427             strlen(GetOxmString(selectedDeviceInfo->doxm->oxmSel)),
428             ptDeviceID.id, sizeof(ptDeviceID.id),
429             selectedDeviceInfo->doxm->deviceID.id, sizeof(selectedDeviceInfo->doxm->deviceID.id),
430             ownerPSK, OWNER_PSK_LENGTH_128);
431
432     if (CA_STATUS_OK == pskRet)
433     {
434         OIC_LOG(INFO, TAG,"ownerPSK dump:\n");
435         OIC_LOG_BUFFER(INFO, TAG,ownerPSK, OWNER_PSK_LENGTH_128);
436         //Generating new credential for provisioning tool
437         OicSecCred_t *cred = GenerateCredential(&selectedDeviceInfo->doxm->deviceID,
438                 SYMMETRIC_PAIR_WISE_KEY, NULL,
439                 &ownerKey, &ptDeviceID);
440         VERIFY_NON_NULL(TAG, cred, ERROR);
441
442         // TODO: Added as workaround. Will be replaced soon.
443         cred->privateData.encoding = OIC_ENCODING_RAW;
444
445 #if 1
446         // NOTE: Test codes to use BASE64 encoded owner PSK.
447         uint32_t outSize = 0;
448         size_t b64BufSize = B64ENCODE_OUT_SAFESIZE((OWNER_PSK_LENGTH_128 + 1));
449         char* b64Buf = (uint8_t *)OICCalloc(1, b64BufSize);
450         VERIFY_NON_NULL(TAG, b64Buf, ERROR);
451         b64Encode(cred->privateData.data, cred->privateData.len, b64Buf, b64BufSize, &outSize);
452
453         OICFree( cred->privateData.data );
454         cred->privateData.data = (uint8_t *)OICCalloc(1, outSize + 1);
455         VERIFY_NON_NULL(TAG, cred->privateData.data, ERROR);
456
457         strncpy(cred->privateData.data, b64Buf, outSize);
458         cred->privateData.data[outSize] = '\0';
459         cred->privateData.encoding = OIC_ENCODING_BASE64;
460         cred->privateData.len = outSize;
461         OICFree(b64Buf);
462 #endif //End of Test codes
463
464         res = AddCredential(cred);
465         if(res != OC_STACK_OK)
466         {
467             DeleteCredList(cred);
468             return res;
469         }
470     }
471     else
472     {
473         OIC_LOG(ERROR, TAG, "CAGenerateOwnerPSK failed");
474     }
475
476     OIC_LOG(DEBUG, TAG, "OUT SaveOwnerPSK");
477 exit:
478     return res;
479 }
480
481 /**
482  * Callback handler for OwnerShipTransferModeHandler API.
483  *
484  * @param[in] ctx             ctx value passed to callback from calling function.
485  * @param[in] UNUSED          handle to an invocation
486  * @param[in] clientResponse  Response from queries to remote servers.
487  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
488  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
489  */
490 static OCStackApplicationResult OwnerTransferModeHandler(void *ctx, OCDoHandle UNUSED,
491                                                          OCClientResponse *clientResponse)
492 {
493     OIC_LOG(DEBUG, TAG, "IN OwnerTransferModeHandler");
494
495     VERIFY_NON_NULL(TAG, clientResponse, WARNING);
496     VERIFY_NON_NULL(TAG, ctx, WARNING);
497
498     OTMContext_t* otmCtx = (OTMContext_t*)ctx;
499     (void)UNUSED;
500     if (OC_STACK_RESOURCE_CHANGED == clientResponse->result)
501     {
502         OIC_LOG(INFO, TAG, "OwnerTransferModeHandler : response result = OC_STACK_OK");
503         //Send request : GET /oic/sec/pstat
504         OCStackResult res = GetProvisioningStatusResource(otmCtx);
505         if(OC_STACK_OK != res)
506         {
507             OIC_LOG(WARNING, TAG, "Failed to get pstat information");
508             SetResult(otmCtx, res);
509         }
510     }
511     else
512     {
513         OIC_LOG_V(WARNING, TAG, "OwnerTransferModeHandler : Client response is incorrect : %d",
514         clientResponse->result);
515         SetResult(otmCtx, clientResponse->result);
516     }
517
518     OIC_LOG(DEBUG, TAG, "OUT OwnerTransferModeHandler");
519
520 exit:
521     return  OC_STACK_DELETE_TRANSACTION;
522 }
523
524 /**
525  * Callback handler for ProvisioningStatusResouceHandler API.
526  *
527  * @param[in] ctx             ctx value passed to callback from calling function.
528  * @param[in] UNUSED          handle to an invocation
529  * @param[in] clientResponse  Response from queries to remote servers.
530  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
531  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
532  */
533 static OCStackApplicationResult ListMethodsHandler(void *ctx, OCDoHandle UNUSED,
534                                                     OCClientResponse *clientResponse)
535 {
536     OIC_LOG(DEBUG, TAG, "IN ListMethodsHandler");
537
538     VERIFY_NON_NULL(TAG, clientResponse, WARNING);
539     VERIFY_NON_NULL(TAG, ctx, WARNING);
540
541     OTMContext_t* otmCtx = (OTMContext_t*)ctx;
542     (void)UNUSED;
543     if  (OC_STACK_OK == clientResponse->result)
544     {
545         if  (NULL == clientResponse->payload)
546         {
547             OIC_LOG(INFO, TAG, "Skiping Null payload");
548             SetResult(otmCtx, OC_STACK_ERROR);
549             return OC_STACK_DELETE_TRANSACTION;
550         }
551
552         if (PAYLOAD_TYPE_SECURITY != clientResponse->payload->type)
553         {
554             OIC_LOG(INFO, TAG, "Unknown payload type");
555             SetResult(otmCtx, OC_STACK_ERROR);
556             return OC_STACK_DELETE_TRANSACTION;
557         }
558         OicSecPstat_t* pstat = NULL;
559         OCStackResult result = CBORPayloadToPstat(
560                 ((OCSecurityPayload*)clientResponse->payload)->securityData,
561                 ((OCSecurityPayload*)clientResponse->payload)->payloadSize,
562                 &pstat);
563         if(NULL == pstat || result != OC_STACK_OK)
564         {
565             OIC_LOG(ERROR, TAG, "Error while converting cbor to pstat.");
566             SetResult(otmCtx, OC_STACK_ERROR);
567             return OC_STACK_DELETE_TRANSACTION;
568         }
569         if(false == (TAKE_OWNER & pstat->cm))
570         {
571             OIC_LOG(ERROR, TAG, "Device pairing mode enabling owner transfer operations is disabled");
572             SetResult(otmCtx, OC_STACK_ERROR);
573             return OC_STACK_DELETE_TRANSACTION;
574         }
575         otmCtx->selectedDeviceInfo->pstat = pstat;
576
577         //Select operation mode (Currently supported SINGLE_SERVICE_CLIENT_DRIVEN only)
578         SelectOperationMode(otmCtx->selectedDeviceInfo, &(otmCtx->selectedDeviceInfo->pstat->om));
579
580         //Send request : POST /oic/sec/pstat [{"om":"bx11", .. }]
581         OCStackResult res = PostUpdateOperationMode(otmCtx);
582         if (OC_STACK_OK != res)
583         {
584             OIC_LOG(ERROR, TAG, "Error while updating operation mode.");
585             SetResult(otmCtx, res);
586         }
587     }
588     else
589     {
590         OIC_LOG_V(WARNING, TAG, "ListMethodsHandler : Client response is incorrect : %d",
591             clientResponse->result);
592         SetResult(otmCtx, clientResponse->result);
593     }
594
595     OIC_LOG(DEBUG, TAG, "OUT ListMethodsHandler");
596 exit:
597     return  OC_STACK_DELETE_TRANSACTION;
598 }
599
600 /**
601  * Response handler for update owner uuid request.
602  *
603  * @param[in] ctx             ctx value passed to callback from calling function.
604  * @param[in] UNUSED          handle to an invocation
605  * @param[in] clientResponse  Response from queries to remote servers.
606  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
607  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
608  */
609 static OCStackApplicationResult OwnerUuidUpdateHandler(void *ctx, OCDoHandle UNUSED,
610                                 OCClientResponse *clientResponse)
611 {
612     VERIFY_NON_NULL(TAG, clientResponse, WARNING);
613     VERIFY_NON_NULL(TAG, ctx, WARNING);
614
615     OIC_LOG(DEBUG, TAG, "IN OwnerUuidUpdateHandler");
616     (void)UNUSED;
617     OCStackResult res = OC_STACK_OK;
618     OTMContext_t* otmCtx = (OTMContext_t*)ctx;
619
620     if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
621     {
622         if(otmCtx && otmCtx->selectedDeviceInfo)
623         {
624             res = SaveOwnerPSK(otmCtx->selectedDeviceInfo);
625             if(OC_STACK_OK != res)
626             {
627                 OIC_LOG(ERROR, TAG, "OwnerUuidUpdateHandler:Failed to owner PSK generation");
628                 SetResult(otmCtx, res);
629                 return OC_STACK_DELETE_TRANSACTION;
630             }
631
632             //POST owner credential to new device according to security spec B.
633             res = PostOwnerCredential(otmCtx);
634             if(OC_STACK_OK != res)
635             {
636                 OIC_LOG(ERROR, TAG,
637                         "OwnerUuidUpdateHandler:Failed to send PosT request for onwer credential");
638                 SetResult(otmCtx, res);
639                 return OC_STACK_DELETE_TRANSACTION;
640             }
641         }
642     }
643     else
644     {
645         res = clientResponse->result;
646         OIC_LOG_V(ERROR, TAG, "OwnerUuidHandler : Unexpected result %d", res);
647         SetResult(otmCtx, res);
648     }
649
650     OIC_LOG(DEBUG, TAG, "OUT OwnerUuidUpdateHandler");
651
652 exit:
653     return  OC_STACK_DELETE_TRANSACTION;
654 }
655
656 /**
657  * Response handler for update operation mode.
658  *
659  * @param[in] ctx             ctx value passed to callback from calling function.
660  * @param[in] UNUSED          handle to an invocation
661  * @param[in] clientResponse  Response from queries to remote servers.
662  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
663  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
664  */
665 static OCStackApplicationResult OperationModeUpdateHandler(void *ctx, OCDoHandle UNUSED,
666                                 OCClientResponse *clientResponse)
667 {
668     OIC_LOG(DEBUG, TAG, "IN OperationModeUpdateHandler");
669
670     VERIFY_NON_NULL(TAG, clientResponse, WARNING);
671     VERIFY_NON_NULL(TAG, ctx, WARNING);
672
673     OTMContext_t* otmCtx = (OTMContext_t*)ctx;
674     (void) UNUSED;
675     if  (OC_STACK_RESOURCE_CHANGED == clientResponse->result)
676     {
677         OCStackResult res = OC_STACK_ERROR;
678         OicSecOxm_t selOxm = otmCtx->selectedDeviceInfo->doxm->oxmSel;
679         //DTLS Handshake
680         //Load secret for temporal secure session.
681         if(g_OTMDatas[selOxm].loadSecretCB)
682         {
683             res = g_OTMDatas[selOxm].loadSecretCB(otmCtx);
684             if(OC_STACK_OK != res)
685             {
686                 OIC_LOG(ERROR, TAG, "OperationModeUpdate : Failed to load secret");
687                 SetResult(otmCtx, res);
688                 return  OC_STACK_DELETE_TRANSACTION;
689             }
690         }
691
692         //It will be used in handshake event handler
693         g_otmCtx = otmCtx;
694
695         //Try DTLS handshake to generate secure session
696         if(g_OTMDatas[selOxm].createSecureSessionCB)
697         {
698             res = g_OTMDatas[selOxm].createSecureSessionCB(otmCtx);
699             if(OC_STACK_OK != res)
700             {
701                 OIC_LOG(ERROR, TAG, "OperationModeUpdate : Failed to create DTLS session");
702                 SetResult(otmCtx, res);
703                 return OC_STACK_DELETE_TRANSACTION;
704             }
705         }
706     }
707     else
708     {
709         OIC_LOG(ERROR, TAG, "Error while update operation mode");
710         SetResult(otmCtx, clientResponse->result);
711     }
712
713     OIC_LOG(DEBUG, TAG, "OUT OperationModeUpdateHandler");
714
715 exit:
716     return  OC_STACK_DELETE_TRANSACTION;
717 }
718
719 /**
720  * Response handler for update owner crendetial request.
721  *
722  * @param[in] ctx             ctx value passed to callback from calling function.
723  * @param[in] UNUSED          handle to an invocation
724  * @param[in] clientResponse  Response from queries to remote servers.
725  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
726  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
727  */
728 static OCStackApplicationResult OwnerCredentialHandler(void *ctx, OCDoHandle UNUSED,
729                                 OCClientResponse *clientResponse)
730 {
731     VERIFY_NON_NULL(TAG, clientResponse, WARNING);
732     VERIFY_NON_NULL(TAG, ctx, WARNING);
733
734     OIC_LOG(DEBUG, TAG, "IN OwnerCredentialHandler");
735     (void)UNUSED;
736     OCStackResult res = OC_STACK_OK;
737     OTMContext_t* otmCtx = (OTMContext_t*)ctx;
738
739     if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
740     {
741         if(otmCtx && otmCtx->selectedDeviceInfo)
742         {
743             //Close the temporal secure session to verify the owner credential
744             CAEndpoint_t* endpoint = (CAEndpoint_t *)&otmCtx->selectedDeviceInfo->endpoint;
745             endpoint->port = otmCtx->selectedDeviceInfo->securePort;
746             CAResult_t caResult = CA_STATUS_OK;
747             if(CA_ADAPTER_IP == endpoint->adapter)
748             {
749                 caResult = CACloseDtlsSession(endpoint);
750             }
751 #ifdef __WITH_TLS__
752             else
753             {
754                 caResult = CAcloseTlsConnection(endpoint);
755             }
756 #endif
757             if(CA_STATUS_OK != caResult)
758             {
759                 OIC_LOG(ERROR, TAG, "Failed to close DTLS session");
760                 SetResult(otmCtx, caResult);
761                 return OC_STACK_DELETE_TRANSACTION;
762             }
763
764             /**
765              * If we select NULL cipher,
766              * client will select appropriate cipher suite according to server's cipher-suite list.
767              */
768             if(CA_ADAPTER_IP == endpoint->adapter)
769             {
770                 caResult = CASelectCipherSuite(TLS_NULL_WITH_NULL_NULL, endpoint->adapter);
771             }
772             else
773             {
774                 // TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256 = 0xC037, /**< see RFC 5489 */
775                 caResult = CASelectCipherSuite(0xC037, endpoint->adapter);
776             }
777
778             if(CA_STATUS_OK != caResult)
779             {
780                 OIC_LOG(ERROR, TAG, "Failed to select TLS_NULL_WITH_NULL_NULL");
781                 SetResult(otmCtx, caResult);
782                 return OC_STACK_DELETE_TRANSACTION;
783             }
784
785             /**
786              * in case of random PIN based OxM,
787              * revert get_psk_info callback of tinyDTLS to use owner credential.
788              */
789             if(OIC_RANDOM_DEVICE_PIN == otmCtx->selectedDeviceInfo->doxm->oxmSel)
790             {
791                 OicUuid_t emptyUuid = { .id={0}};
792                 SetUuidForRandomPinOxm(&emptyUuid);
793
794                 if(CA_ADAPTER_IP == endpoint->adapter)
795                 {
796                     caResult = CARegisterDTLSCredentialsHandler(GetDtlsPskCredentials);
797                 }
798 #ifdef __WITH_TLS__
799                 else
800                 {
801                     caResult = CAregisterTlsCredentialsHandler(GetDtlsPskCredentials);
802                 }
803 #endif
804
805                 if(CA_STATUS_OK != caResult)
806                 {
807                     OIC_LOG(ERROR, TAG, "Failed to revert DTLS credential handler.");
808                     SetResult(otmCtx, OC_STACK_INVALID_CALLBACK);
809                     return OC_STACK_DELETE_TRANSACTION;
810                 }
811             }
812 #ifdef __WITH_TLS__
813            otmCtx->selectedDeviceInfo->connType |= CT_FLAG_SECURE;
814 #endif
815             //POST /oic/sec/doxm [{ ..., "owned":"TRUE" }]
816             res = PostOwnershipInformation(otmCtx);
817             if(OC_STACK_OK != res)
818             {
819                 OIC_LOG(ERROR, TAG, "Failed to post ownership information to new device");
820                 SetResult(otmCtx, res);
821                 return OC_STACK_DELETE_TRANSACTION;
822             }
823         }
824     }
825     else
826     {
827         res = clientResponse->result;
828         OIC_LOG_V(ERROR, TAG, "OwnerCredentialHandler : Unexpected result %d", res);
829         SetResult(otmCtx, res);
830     }
831
832     OIC_LOG(DEBUG, TAG, "OUT OwnerCredentialHandler");
833
834 exit:
835     return  OC_STACK_DELETE_TRANSACTION;
836 }
837
838
839 /**
840  * Response handler for update owner information request.
841  *
842  * @param[in] ctx             ctx value passed to callback from calling function.
843  * @param[in] UNUSED          handle to an invocation
844  * @param[in] clientResponse  Response from queries to remote servers.
845  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
846  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
847  */
848 static OCStackApplicationResult OwnershipInformationHandler(void *ctx, OCDoHandle UNUSED,
849                                 OCClientResponse *clientResponse)
850 {
851     VERIFY_NON_NULL(TAG, clientResponse, WARNING);
852     VERIFY_NON_NULL(TAG, ctx, WARNING);
853
854     OIC_LOG(DEBUG, TAG, "IN OwnershipInformationHandler");
855     (void)UNUSED;
856     OCStackResult res = OC_STACK_OK;
857     OTMContext_t* otmCtx = (OTMContext_t*)ctx;
858
859     if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
860     {
861         if(otmCtx && otmCtx->selectedDeviceInfo)
862         {
863             OIC_LOG(INFO, TAG, "Ownership transfer was successfully completed.");
864             OIC_LOG(INFO, TAG, "Set Ready for provisioning state .");
865
866             res = PostProvisioningStatus(otmCtx);
867             if(OC_STACK_OK != res)
868             {
869                 OIC_LOG(ERROR, TAG, "Failed to update pstat");
870                 SetResult(otmCtx, res);
871             }
872         }
873     }
874     else
875     {
876         res = clientResponse->result;
877         OIC_LOG_V(ERROR, TAG, "OwnershipInformationHandler : Unexpected result %d", res);
878         SetResult(otmCtx, res);
879     }
880
881     OIC_LOG(DEBUG, TAG, "OUT OwnershipInformationHandler");
882
883 exit:
884     return  OC_STACK_DELETE_TRANSACTION;
885 }
886
887 /**
888  * Response handler of update provisioning status.
889  *
890  * @param[in] ctx             ctx value passed to callback from calling function.
891  * @param[in] UNUSED          handle to an invocation
892  * @param[in] clientResponse  Response from queries to remote servers.
893  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
894  *          and OC_STACK_KEEP_TRANSACTION to keep it.
895  */
896 static OCStackApplicationResult ProvisioningStatusHandler(void *ctx, OCDoHandle UNUSED,
897                                                        OCClientResponse *clientResponse)
898 {
899     OIC_LOG_V(INFO, TAG, "IN ProvisioningStatusHandler.");
900
901     VERIFY_NON_NULL(TAG, clientResponse, ERROR);
902     VERIFY_NON_NULL(TAG, ctx, ERROR);
903
904     OTMContext_t* otmCtx = (OTMContext_t*) ctx;
905     (void)UNUSED;
906     OCStackResult res = OC_STACK_OK;
907
908     if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
909     {
910         if(otmCtx && otmCtx->selectedDeviceInfo)
911         {
912             OIC_LOG(INFO, TAG, "Device state is in Ready for Provisionig.");
913
914             res = PostNormalOperationStatus(otmCtx);
915             if(OC_STACK_OK != res)
916             {
917                 OIC_LOG(ERROR, TAG, "Failed to update pstat");
918                 SetResult(otmCtx, res);
919             }
920         }
921     }
922     else
923     {
924         OIC_LOG_V(INFO, TAG, "Error occured in provisionDefaultACLCB :: %d\n",
925                             clientResponse->result);
926         SetResult(otmCtx, clientResponse->result);
927     }
928
929 exit:
930     OIC_LOG_V(INFO, TAG, "OUT ProvisioningStatusHandler.");
931     return OC_STACK_DELETE_TRANSACTION;
932 }
933
934 /**
935  * Response handler of update provisioning status to Ready for Normal..
936  *
937  * @param[in] ctx             ctx value passed to callback from calling function.
938  * @param[in] UNUSED          handle to an invocation
939  * @param[in] clientResponse  Response from queries to remote servers.
940  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
941  *          and OC_STACK_KEEP_TRANSACTION to keep it.
942  */
943 static OCStackApplicationResult ReadyForNomalStatusHandler(void *ctx, OCDoHandle UNUSED,
944                                                        OCClientResponse *clientResponse)
945 {
946     OIC_LOG_V(INFO, TAG, "IN ReadyForNomalStatusHandler.");
947
948     VERIFY_NON_NULL(TAG, clientResponse, ERROR);
949     VERIFY_NON_NULL(TAG, ctx, ERROR);
950
951     OTMContext_t* otmCtx = (OTMContext_t*) ctx;
952     (void)UNUSED;
953
954     if (OC_STACK_RESOURCE_CHANGED == clientResponse->result)
955     {
956         OIC_LOG(INFO, TAG, "Device state is in Ready for Normal Operation.");
957         OCStackResult res = PDMAddDevice(&otmCtx->selectedDeviceInfo->doxm->deviceID);
958          if (OC_STACK_OK == res)
959          {
960                 OIC_LOG_V(INFO, TAG, "Add device's UUID in PDM_DB");
961                 SetResult(otmCtx, OC_STACK_OK);
962                 return OC_STACK_DELETE_TRANSACTION;
963          }
964           else
965          {
966               OIC_LOG(ERROR, TAG, "Ownership transfer is complete but adding information to DB is failed.");
967          }
968     }
969     else
970     {
971         OIC_LOG_V(INFO, TAG, "Error occured in provisionDefaultACLCB :: %d\n",
972                             clientResponse->result);
973         SetResult(otmCtx, clientResponse->result);
974     }
975
976 exit:
977     OIC_LOG_V(INFO, TAG, "OUT ReadyForNomalStatusHandler.");
978     return OC_STACK_DELETE_TRANSACTION;
979 }
980
981 static OCStackResult PostOwnerCredential(OTMContext_t* otmCtx)
982 {
983     OIC_LOG(DEBUG, TAG, "IN PostOwnerCredential");
984
985     if(!otmCtx || !otmCtx->selectedDeviceInfo)
986     {
987         OIC_LOG(ERROR, TAG, "Invalid parameters");
988         return OC_STACK_INVALID_PARAM;
989     }
990
991     OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
992     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
993
994     if(!PMGenerateQuery(true,
995                         deviceInfo->endpoint.addr, deviceInfo->securePort,
996                         deviceInfo->connType,
997                         query, sizeof(query), OIC_RSRC_CRED_URI))
998     {
999         OIC_LOG(ERROR, TAG, "PostOwnerCredential : Failed to generate query");
1000         return OC_STACK_ERROR;
1001     }
1002     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1003     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1004     if(!secPayload)
1005     {
1006         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1007         return OC_STACK_NO_MEMORY;
1008     }
1009
1010     //Generate owner credential for new device
1011     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1012     const OicSecCred_t* ownerCredential = GetCredResourceData(&(deviceInfo->doxm->deviceID));
1013     if(!ownerCredential)
1014     {
1015         OIC_LOG(ERROR, TAG, "Can not find OwnerPSK.");
1016         return OC_STACK_NO_RESOURCE;
1017     }
1018
1019     OicUuid_t credSubjectId = {.id={0}};
1020     if(OC_STACK_OK == GetDoxmDeviceID(&credSubjectId))
1021     {
1022         OicSecCred_t newCredential;
1023         memcpy(&newCredential, ownerCredential, sizeof(OicSecCred_t));
1024         newCredential.next = NULL;
1025
1026         //Set subject ID as PT's ID
1027         memcpy(&(newCredential.subject), &credSubjectId, sizeof(OicUuid_t));
1028
1029         //Fill private data as empty string
1030         newCredential.privateData.data = "";
1031         newCredential.privateData.len = 0;
1032         newCredential.privateData.encoding = ownerCredential->privateData.encoding;
1033 #ifdef __WITH_X509__
1034         newCredential.publicData.data = NULL;
1035         newCredential.publicData.len = 0;
1036 #endif
1037         int secureFlag = 0;
1038         //Send owner credential to new device : POST /oic/sec/cred [ owner credential ]
1039         if (OC_STACK_OK != CredToCBORPayload(&newCredential, &secPayload->securityData,
1040                                         &secPayload->payloadSize, secureFlag))
1041         {
1042             OICFree(secPayload);
1043             OIC_LOG(ERROR, TAG, "Error while converting bin to cbor.");
1044             return OC_STACK_ERROR;
1045         }
1046         OIC_LOG(DEBUG, TAG, "Cred Payload:");
1047         OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
1048
1049         OCCallbackData cbData;
1050         cbData.cb = &OwnerCredentialHandler;
1051         cbData.context = (void *)otmCtx;
1052         cbData.cd = NULL;
1053         OCStackResult res = OCDoResource(NULL, OC_REST_POST, query,
1054                                          &deviceInfo->endpoint, (OCPayload*)secPayload,
1055                                          deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1056         if (res != OC_STACK_OK)
1057         {
1058             OIC_LOG(ERROR, TAG, "OCStack resource error");
1059         }
1060     }
1061     else
1062     {
1063         OIC_LOG(ERROR, TAG, "Failed to read DOXM device ID.");
1064         return OC_STACK_NO_RESOURCE;
1065     }
1066
1067     OIC_LOG(DEBUG, TAG, "OUT PostOwnerCredential");
1068
1069     return OC_STACK_OK;
1070 }
1071
1072 static OCStackResult PostOwnerTransferModeToResource(OTMContext_t* otmCtx)
1073 {
1074     OIC_LOG(DEBUG, TAG, "IN PostOwnerTransferModeToResource");
1075
1076     if(!otmCtx || !otmCtx->selectedDeviceInfo)
1077     {
1078         OIC_LOG(ERROR, TAG, "Invalid parameters");
1079         return OC_STACK_INVALID_PARAM;
1080     }
1081
1082     OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1083     OicSecOxm_t selectedOxm = deviceInfo->doxm->oxmSel;
1084     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1085
1086     if(!PMGenerateQuery(false,
1087                         deviceInfo->endpoint.addr, deviceInfo->endpoint.port,
1088                         deviceInfo->connType,
1089                         query, sizeof(query), OIC_RSRC_DOXM_URI))
1090     {
1091         OIC_LOG(ERROR, TAG, "PostOwnerTransferModeToResource : Failed to generate query");
1092         return OC_STACK_ERROR;
1093     }
1094     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1095     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1096     if(!secPayload)
1097     {
1098         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1099         return OC_STACK_NO_MEMORY;
1100     }
1101     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1102     OCStackResult res = g_OTMDatas[selectedOxm].createSelectOxmPayloadCB(otmCtx,
1103             &secPayload->securityData, &secPayload->payloadSize);
1104     if (OC_STACK_OK != res && NULL == secPayload->securityData)
1105     {
1106         OCPayloadDestroy((OCPayload *)secPayload);
1107         OIC_LOG(ERROR, TAG, "Error while converting bin to cbor");
1108         return OC_STACK_ERROR;
1109     }
1110
1111     OCCallbackData cbData;
1112     cbData.cb = &OwnerTransferModeHandler;
1113     cbData.context = (void *)otmCtx;
1114     cbData.cd = NULL;
1115     res = OCDoResource(NULL, OC_REST_POST, query,
1116                        &deviceInfo->endpoint, (OCPayload *)secPayload,
1117                        deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1118     if (res != OC_STACK_OK)
1119     {
1120         OIC_LOG(ERROR, TAG, "OCStack resource error");
1121     }
1122
1123     OIC_LOG(DEBUG, TAG, "OUT PostOwnerTransferModeToResource");
1124
1125     return res;
1126 }
1127
1128 static OCStackResult GetProvisioningStatusResource(OTMContext_t* otmCtx)
1129 {
1130     OIC_LOG(DEBUG, TAG, "IN GetProvisioningStatusResource");
1131
1132     if(!otmCtx || !otmCtx->selectedDeviceInfo)
1133     {
1134         OIC_LOG(ERROR, TAG, "Invailed parameters");
1135         return OC_STACK_INVALID_PARAM;
1136     }
1137
1138     OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1139     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1140     if(!PMGenerateQuery(false,
1141                         deviceInfo->endpoint.addr, deviceInfo->endpoint.port,
1142                         deviceInfo->connType,
1143                         query, sizeof(query), OIC_RSRC_PSTAT_URI))
1144     {
1145         OIC_LOG(ERROR, TAG, "GetProvisioningStatusResource : Failed to generate query");
1146         return OC_STACK_ERROR;
1147     }
1148     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1149
1150     OCCallbackData cbData;
1151     cbData.cb = &ListMethodsHandler;
1152     cbData.context = (void *)otmCtx;
1153     cbData.cd = NULL;
1154     OCStackResult res = OCDoResource(NULL, OC_REST_GET, query, NULL, NULL,
1155                                      deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1156     if (res != OC_STACK_OK)
1157     {
1158         OIC_LOG(ERROR, TAG, "OCStack resource error");
1159     }
1160
1161     OIC_LOG(DEBUG, TAG, "OUT GetProvisioningStatusResource");
1162
1163     return res;
1164 }
1165
1166 static OCStackResult PostOwnerUuid(OTMContext_t* otmCtx)
1167 {
1168     OIC_LOG(DEBUG, TAG, "IN PostOwnerUuid");
1169
1170     if(!otmCtx || !otmCtx->selectedDeviceInfo)
1171     {
1172         OIC_LOG(ERROR, TAG, "Invailed parameters");
1173         return OC_STACK_INVALID_PARAM;
1174     }
1175
1176     OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1177     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1178     if(!PMGenerateQuery(true,
1179                         deviceInfo->endpoint.addr, deviceInfo->securePort,
1180                         deviceInfo->connType,
1181                         query, sizeof(query), OIC_RSRC_DOXM_URI))
1182     {
1183         OIC_LOG(ERROR, TAG, "PostOwnerUuid : Failed to generate query");
1184         return OC_STACK_ERROR;
1185     }
1186     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1187
1188     //Post PT's uuid to new device
1189     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1190     if(!secPayload)
1191     {
1192         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1193         return OC_STACK_NO_MEMORY;
1194     }
1195     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1196     OCStackResult res =  g_OTMDatas[deviceInfo->doxm->oxmSel].createOwnerTransferPayloadCB(
1197             otmCtx, &secPayload->securityData, &secPayload->payloadSize);
1198     if (OC_STACK_OK != res && NULL == secPayload->securityData)
1199     {
1200         OCPayloadDestroy((OCPayload *)secPayload);
1201         OIC_LOG(ERROR, TAG, "Error while converting doxm bin to cbor.");
1202         return OC_STACK_INVALID_PARAM;
1203     }
1204     OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
1205
1206     OCCallbackData cbData;
1207     cbData.cb = &OwnerUuidUpdateHandler;
1208     cbData.context = (void *)otmCtx;
1209     cbData.cd = NULL;
1210
1211     res = OCDoResource(NULL, OC_REST_POST, query, 0, (OCPayload *)secPayload,
1212             deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1213     if (res != OC_STACK_OK)
1214     {
1215         OIC_LOG(ERROR, TAG, "OCStack resource error");
1216     }
1217
1218     OIC_LOG(DEBUG, TAG, "OUT PostOwnerUuid");
1219
1220     return res;
1221 }
1222
1223 static OCStackResult PostOwnershipInformation(OTMContext_t* otmCtx)
1224 {
1225     OIC_LOG(DEBUG, TAG, "IN PostOwnershipInformation");
1226
1227     if(!otmCtx || !otmCtx->selectedDeviceInfo)
1228     {
1229         OIC_LOG(ERROR, TAG, "Invailed parameters");
1230         return OC_STACK_INVALID_PARAM;
1231     }
1232
1233     OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1234     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1235     if(!PMGenerateQuery(true,
1236                         deviceInfo->endpoint.addr, deviceInfo->securePort,
1237                         deviceInfo->connType,
1238                         query, sizeof(query), OIC_RSRC_DOXM_URI))
1239     {
1240         OIC_LOG(ERROR, TAG, "PostOwnershipInformation : Failed to generate query");
1241         return OC_STACK_ERROR;
1242     }
1243     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1244
1245     //OwnershipInformationHandler
1246     OCSecurityPayload *secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1247     if (!secPayload)
1248     {
1249         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1250         return OC_STACK_NO_MEMORY;
1251     }
1252
1253     otmCtx->selectedDeviceInfo->doxm->owned = true;
1254
1255     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1256     OCStackResult res = DoxmToCBORPayload(otmCtx->selectedDeviceInfo->doxm,
1257             &secPayload->securityData, &secPayload->payloadSize, true);
1258     if (OC_STACK_OK != res && NULL == secPayload->securityData)
1259     {
1260         OCPayloadDestroy((OCPayload *)secPayload);
1261         OIC_LOG(ERROR, TAG, "Error while converting doxm bin to json");
1262         return OC_STACK_INVALID_PARAM;
1263     }
1264
1265     OCCallbackData cbData;
1266     cbData.cb = &OwnershipInformationHandler;
1267     cbData.context = (void *)otmCtx;
1268     cbData.cd = NULL;
1269
1270     res = OCDoResource(NULL, OC_REST_POST, query, 0, (OCPayload*)secPayload,
1271                        deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1272     if (res != OC_STACK_OK)
1273     {
1274         OIC_LOG(ERROR, TAG, "OCStack resource error");
1275     }
1276
1277     OIC_LOG(DEBUG, TAG, "OUT PostOwnershipInformation");
1278
1279     return res;
1280 }
1281
1282 static OCStackResult PostUpdateOperationMode(OTMContext_t* otmCtx)
1283 {
1284     OIC_LOG(DEBUG, TAG, "IN PostUpdateOperationMode");
1285
1286     if(!otmCtx || !otmCtx->selectedDeviceInfo)
1287     {
1288         return OC_STACK_INVALID_PARAM;
1289     }
1290
1291     OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1292     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1293     if(!PMGenerateQuery(false,
1294                         deviceInfo->endpoint.addr, deviceInfo->endpoint.port,
1295                         deviceInfo->connType,
1296                         query, sizeof(query), OIC_RSRC_PSTAT_URI))
1297     {
1298         OIC_LOG(ERROR, TAG, "PostUpdateOperationMode : Failed to generate query");
1299         return OC_STACK_ERROR;
1300     }
1301     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1302
1303     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1304     if(!secPayload)
1305     {
1306         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1307         return OC_STACK_NO_MEMORY;
1308     }
1309     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1310     OCStackResult res = PstatToCBORPayload(deviceInfo->pstat, &secPayload->securityData,
1311                                            &secPayload->payloadSize, true);
1312    if (OC_STACK_OK != res)
1313     {
1314         OCPayloadDestroy((OCPayload *)secPayload);
1315         OIC_LOG(ERROR, TAG, "Error while converting pstat to cbor.");
1316         return OC_STACK_INVALID_PARAM;
1317     }
1318
1319     OCCallbackData cbData;
1320     cbData.cb = &OperationModeUpdateHandler;
1321     cbData.context = (void *)otmCtx;
1322     cbData.cd = NULL;
1323     res = OCDoResource(NULL, OC_REST_POST, query, 0, (OCPayload *)secPayload,
1324                        deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1325     if (res != OC_STACK_OK)
1326     {
1327         OIC_LOG(ERROR, TAG, "OCStack resource error");
1328     }
1329
1330     OIC_LOG(DEBUG, TAG, "OUT PostUpdateOperationMode");
1331
1332     return res;
1333 }
1334
1335 static OCStackResult StartOwnershipTransfer(void* ctx, OCProvisionDev_t* selectedDevice)
1336 {
1337     OIC_LOG(INFO, TAG, "IN StartOwnershipTransfer");
1338     OTMContext_t* otmCtx = (OTMContext_t*)ctx;
1339     otmCtx->selectedDeviceInfo = selectedDevice;
1340
1341     //Set to the lowest level OxM, and then find more higher level OxM.
1342     OCStackResult res = SelectProvisioningMethod(selectedDevice->doxm->oxm,
1343                                                  selectedDevice->doxm->oxmLen,
1344                                                  &selectedDevice->doxm->oxmSel);
1345     if(OC_STACK_OK != res)
1346     {
1347         OIC_LOG(ERROR, TAG, "Failed to select the provisioning method");
1348         SetResult(otmCtx, res);
1349         return res;
1350     }
1351     OIC_LOG_V(DEBUG, TAG, "Selected provisoning method = %d", selectedDevice->doxm->oxmSel);
1352
1353     //Send Req: POST /oic/sec/doxm [{..."OxmSel" :g_OTMDatas[Index of Selected OxM].OXMString,...}]
1354     res = PostOwnerTransferModeToResource(otmCtx);
1355     if(OC_STACK_OK != res)
1356     {
1357         OIC_LOG(WARNING, TAG, "Failed to select the provisioning method");
1358         SetResult(otmCtx, res);
1359         return res;
1360     }
1361
1362     //Register DTLS event handler to catch the dtls event while handshake
1363     if(CA_ADAPTER_IP == ((CAEndpoint_t*)(&otmCtx->selectedDeviceInfo->endpoint))->adapter)
1364     {
1365         if(CA_STATUS_OK != CARegisterDTLSCredentialsHandler(GetDtlsPskCredentials))
1366         {
1367             OIC_LOG(WARNING, TAG, "Failed to register DTLS handshake callback.");
1368         }
1369     }
1370 #ifdef __WITH_TLS__
1371     else
1372     {
1373         if(CA_STATUS_OK != CAregisterTlsCredentialsHandler(GetDtlsPskCredentials))
1374         {
1375             OIC_LOG(WARNING, TAG, "Failed to register TLS handshake callback.");
1376         }
1377     }
1378 #endif
1379
1380     OIC_LOG(INFO, TAG, "OUT StartOwnershipTransfer");
1381
1382     return res;
1383
1384 }
1385
1386 OCStackResult OTMSetOwnershipTransferCallbackData(OicSecOxm_t oxmType, OTMCallbackData_t* data)
1387 {
1388     OIC_LOG(DEBUG, TAG, "IN OTMSetOwnerTransferCallbackData");
1389
1390     if(!data)
1391     {
1392         OIC_LOG(ERROR, TAG, "OTMSetOwnershipTransferCallbackData : Invalid parameters");
1393         return OC_STACK_INVALID_PARAM;
1394     }
1395     if(oxmType >= OIC_OXM_COUNT)
1396     {
1397         OIC_LOG(INFO, TAG, "Unknow ownership transfer method");
1398         return OC_STACK_INVALID_PARAM;
1399     }
1400
1401     g_OTMDatas[oxmType].loadSecretCB= data->loadSecretCB;
1402     g_OTMDatas[oxmType].createSecureSessionCB = data->createSecureSessionCB;
1403     g_OTMDatas[oxmType].createSelectOxmPayloadCB = data->createSelectOxmPayloadCB;
1404     g_OTMDatas[oxmType].createOwnerTransferPayloadCB = data->createOwnerTransferPayloadCB;
1405
1406     OIC_LOG(DEBUG, TAG, "OUT OTMSetOwnerTransferCallbackData");
1407
1408     return OC_STACK_OK;
1409 }
1410
1411 /**
1412  * NOTE : Unowned discovery should be done before performing OTMDoOwnershipTransfer
1413  */
1414 OCStackResult OTMDoOwnershipTransfer(void* ctx,
1415                                      OCProvisionDev_t *selectedDevicelist,
1416                                      OCProvisionResultCB resultCallback)
1417 {
1418     OIC_LOG(DEBUG, TAG, "IN OTMDoOwnershipTransfer");
1419
1420     if (NULL == selectedDevicelist)
1421     {
1422         return OC_STACK_INVALID_PARAM;
1423     }
1424     if (NULL == resultCallback)
1425     {
1426         return OC_STACK_INVALID_CALLBACK;
1427     }
1428
1429     OTMContext_t* otmCtx = (OTMContext_t*)OICCalloc(1,sizeof(OTMContext_t));
1430     if(!otmCtx)
1431     {
1432         OIC_LOG(ERROR, TAG, "Failed to create OTM Context");
1433         return OC_STACK_NO_MEMORY;
1434     }
1435     otmCtx->ctxResultCallback = resultCallback;
1436     otmCtx->ctxHasError = false;
1437     otmCtx->userCtx = ctx;
1438     OCProvisionDev_t* pCurDev = selectedDevicelist;
1439
1440     //Counting number of selected devices.
1441     otmCtx->ctxResultArraySize = 0;
1442     while(NULL != pCurDev)
1443     {
1444         otmCtx->ctxResultArraySize++;
1445         pCurDev = pCurDev->next;
1446     }
1447
1448     otmCtx->ctxResultArray =
1449         (OCProvisionResult_t*)OICCalloc(otmCtx->ctxResultArraySize, sizeof(OCProvisionResult_t));
1450     if(NULL == otmCtx->ctxResultArray)
1451     {
1452         OIC_LOG(ERROR, TAG, "OTMDoOwnershipTransfer : Failed to memory allocation");
1453         OICFree(otmCtx);
1454         return OC_STACK_NO_MEMORY;
1455     }
1456     pCurDev = selectedDevicelist;
1457
1458     OCStackResult res = OC_STACK_OK;
1459     //Fill the device UUID for result array.
1460     for(size_t devIdx = 0; devIdx < otmCtx->ctxResultArraySize; devIdx++)
1461     {
1462         //Checking duplication of Device ID.
1463         bool isDuplicate = true;
1464         res = PDMIsDuplicateDevice(&pCurDev->doxm->deviceID, &isDuplicate);
1465         if (OC_STACK_OK != res)
1466         {
1467             goto error;
1468         }
1469         if (isDuplicate)
1470         {
1471             bool isStale = false;
1472             res = PDMIsDeviceStale(&pCurDev->doxm->deviceID, &isStale);
1473             if(OC_STACK_OK != res)
1474             {
1475                 OIC_LOG(ERROR, TAG, "Internal error in PDMIsDeviceStale");
1476                 goto error;
1477             }
1478             if(isStale)
1479             {
1480                 OIC_LOG(INFO, TAG, "Detected duplicated UUID in stale status, "\
1481                                    "this UUID will be removed from PDM");
1482
1483                 res = PDMDeleteDevice(&pCurDev->doxm->deviceID);
1484                 if(OC_STACK_OK != res)
1485                 {
1486                     OIC_LOG(ERROR, TAG, "Internal error in PDMDeleteDevice");
1487                     goto error;
1488                 }
1489             }
1490             else
1491             {
1492                 OIC_LOG(ERROR, TAG, "OTMDoOwnershipTransfer : Device UUID is duplicated");
1493                 res = OC_STACK_INVALID_PARAM;
1494                 goto error;
1495             }
1496         }
1497         memcpy(otmCtx->ctxResultArray[devIdx].deviceId.id,
1498                pCurDev->doxm->deviceID.id,
1499                UUID_LENGTH);
1500         otmCtx->ctxResultArray[devIdx].res = OC_STACK_CONTINUE;
1501         pCurDev = pCurDev->next;
1502     }
1503
1504     StartOwnershipTransfer(otmCtx, selectedDevicelist);
1505
1506     OIC_LOG(DEBUG, TAG, "OUT OTMDoOwnershipTransfer");
1507     return OC_STACK_OK;
1508
1509 error:
1510     OICFree(otmCtx->ctxResultArray);
1511     OICFree(otmCtx);
1512     return res;
1513 }
1514
1515 OCStackResult PostProvisioningStatus(OTMContext_t* otmCtx)
1516 {
1517     OIC_LOG(INFO, TAG, "IN PostProvisioningStatus");
1518
1519     if(!otmCtx || !otmCtx->selectedDeviceInfo)
1520     {
1521         OIC_LOG(ERROR, TAG, "OTMContext is NULL");
1522         return OC_STACK_INVALID_PARAM;
1523     }
1524
1525     //Change the TAKE_OWNER bit of CM to 0.
1526     otmCtx->selectedDeviceInfo->pstat->cm &= (~TAKE_OWNER);
1527
1528     OCSecurityPayload *secPayload = (OCSecurityPayload *)OICCalloc(1, sizeof(OCSecurityPayload));
1529     if (!secPayload)
1530     {
1531         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1532         return OC_STACK_NO_MEMORY;
1533     }
1534     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1535     if (OC_STACK_OK != PstatToCBORPayload(otmCtx->selectedDeviceInfo->pstat,
1536             &secPayload->securityData, &secPayload->payloadSize, true))
1537     {
1538         OCPayloadDestroy((OCPayload *)secPayload);
1539         return OC_STACK_INVALID_JSON;
1540     }
1541     OIC_LOG(DEBUG, TAG, "Created payload for chage to Provisiong state");
1542     OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
1543
1544     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1545     if(!PMGenerateQuery(true,
1546                         otmCtx->selectedDeviceInfo->endpoint.addr,
1547                         otmCtx->selectedDeviceInfo->securePort,
1548                         otmCtx->selectedDeviceInfo->connType,
1549                         query, sizeof(query), OIC_RSRC_PSTAT_URI))
1550     {
1551         OIC_LOG(ERROR, TAG, "PostProvisioningStatus : Failed to generate query");
1552         return OC_STACK_ERROR;
1553     }
1554     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1555
1556     OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL};
1557     cbData.cb = &ProvisioningStatusHandler;
1558     cbData.context = (void*)otmCtx;
1559     cbData.cd = NULL;
1560     OCStackResult ret = OCDoResource(NULL, OC_REST_POST, query, 0, (OCPayload*)secPayload,
1561             otmCtx->selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1562     OIC_LOG_V(INFO, TAG, "OCDoResource returned: %d",ret);
1563     if (ret != OC_STACK_OK)
1564     {
1565         OIC_LOG(ERROR, TAG, "OCStack resource error");
1566     }
1567
1568     OIC_LOG(INFO, TAG, "OUT PostProvisioningStatus");
1569
1570     return ret;
1571 }
1572
1573 OCStackResult PostNormalOperationStatus(OTMContext_t* otmCtx)
1574 {
1575     OIC_LOG(INFO, TAG, "IN PostNormalOperationStatus");
1576
1577     if(!otmCtx || !otmCtx->selectedDeviceInfo)
1578     {
1579         OIC_LOG(ERROR, TAG, "OTMContext is NULL");
1580         return OC_STACK_INVALID_PARAM;
1581     }
1582
1583     //Set isop to true.
1584     otmCtx->selectedDeviceInfo->pstat->isOp = true;
1585
1586     OCSecurityPayload *secPayload = (OCSecurityPayload *)OICCalloc(1, sizeof(OCSecurityPayload));
1587     if (!secPayload)
1588     {
1589         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1590         return OC_STACK_NO_MEMORY;
1591     }
1592     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1593     if (OC_STACK_OK != PstatToCBORPayload(otmCtx->selectedDeviceInfo->pstat,
1594             &secPayload->securityData, &secPayload->payloadSize, true))
1595     {
1596         OCPayloadDestroy((OCPayload *)secPayload);
1597         return OC_STACK_INVALID_JSON;
1598     }
1599     OIC_LOG(DEBUG, TAG, "Created payload for chage to Provisiong state");
1600     OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
1601
1602     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1603     if(!PMGenerateQuery(true,
1604                         otmCtx->selectedDeviceInfo->endpoint.addr,
1605                         otmCtx->selectedDeviceInfo->securePort,
1606                         otmCtx->selectedDeviceInfo->connType,
1607                         query, sizeof(query), OIC_RSRC_PSTAT_URI))
1608     {
1609         OIC_LOG(ERROR, TAG, "PostNormalOperationStatus : Failed to generate query");
1610         return OC_STACK_ERROR;
1611     }
1612     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1613
1614     OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL};
1615     cbData.cb = &ReadyForNomalStatusHandler;
1616     cbData.context = (void*)otmCtx;
1617     cbData.cd = NULL;
1618     OCStackResult ret = OCDoResource(NULL, OC_REST_POST, query, 0, (OCPayload*)secPayload,
1619             otmCtx->selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1620     OIC_LOG_V(INFO, TAG, "OCDoResource returned: %d",ret);
1621     if (ret != OC_STACK_OK)
1622     {
1623         OIC_LOG(ERROR, TAG, "OCStack resource error");
1624     }
1625
1626     OIC_LOG(INFO, TAG, "OUT PostNormalOperationStatus");
1627
1628     return ret;
1629 }