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