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