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