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