Tizen 2.0 Release
[framework/system/oma-dm-agent.git] / src / agent / serviceadapter / dm-phase-handler / dm_phase_handler.c
1 /*
2  * oma-dm-agent
3  * Copyright (c) 2012 Samsung Electronics Co., Ltd.
4  *
5  * Licensed under the Apache License, Version 2.0 (the License);
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 /*sync-agent*/
19 #include <sync_agent.h>
20
21 /*dm-agent*/
22 #include "common/dm_common_def.h"
23 #include "common/dm_common.h"
24 #include "common/util/util.h"
25 #include "serviceadapter/dm-phase-handler/dm_phase_handler.h"
26 #include "serviceadapter/protocolbinder/syncml_protocol_binder.h"
27 #include "serviceadapter/sa_define.h"
28 #include "serviceadapter/sa_syncml_binders.h"
29 #include "serviceadapter/sa_elements.h"
30 #include "serviceadapter/sa_elements_internal.h"
31 #include "serviceadapter/sa_command.h"
32 #include "serviceadapter/sa_command_internal.h"
33 #include "serviceadapter/sa_session.h"
34 #include "serviceadapter/sa_session_internal.h"
35 #include "serviceadapter/sa_util.h"
36 #include "serviceadapter/networkbinder/na_binder.h"
37 #include "mo-handler/dm_mo_common.h"
38 #include "mo-handler/dm_mo_handler.h"
39 #include "dm-engine/dm_common_engine.h"
40
41 #ifndef OMADM_AGENT_LOG
42 #undef LOG_TAG
43 #define LOG_TAG "OMA_DM_CONTEXT"
44 #endif
45
46 #define MAX_SESSION_COUNT 5
47
48 /*temp size*/
49 #define LARGE_OBJECT_SIZE 10000
50
51 static int file_count = 0;
52
53 /*static ErrorType get_AccountInfo(int accountId, char **id, char **pwd, char **serverUrl, int *isBase64, char **nextNonce);*/
54 static DM_ERROR __get_dmaccInfo(char *pServer_id, char **client_id, char **client_pwd, char **sourceUrl, char **targetUrl, int *isBase64, char **nextNonce);
55 static DM_ERROR __check_hmac(Session ** session, char *msg, unsigned int msg_size);
56 static DM_ERROR __create_authentication(Session ** session, char *client_id, char *client_pwd, int isBase64, char *nextNonce);
57 static DM_ERROR ___generater_deviceInfo_replacecmd(Command ** pReplaceCommand);
58 static DM_ERROR __create_devinfo_replace_cmd(Session * session, Command ** pCommand);
59 static DM_ERROR _generate_setupphase_msg(Session ** session, char *pServer_id, char *pSession_id, int session_type, char **msg, unsigned int *msg_size);
60 static DM_ERROR _generate_management_msg(Session ** session, char **msg, unsigned int *msg_size);
61 static DM_ERROR _generate_generic_alert(Session ** session, char *pServer_id, char *pSession_id, char **msg, int *msg_size, int service_engine_id, int result);
62 static DM_ERROR _send_msg(char *accType, int transportType, Session ** session, char *server_url, GList * header_info, char *sendMsg, unsigned int sendMsg_length, GList ** recv_header, char **recvMsg, unsigned int *recvMsg_length);
63 static DM_ERROR _recv_msg(Session ** session, char *recvMsg, unsigned int recvMsg_length, ENGINE_ID * service_engine_id, int *isFinish, int isgeneticAlert);
64
65 static DM_ERROR __get_dmaccInfo(char *pServer_id, char **client_id, char **client_pwd, char **sourceUrl, char **targetUrl, int *isBase64, char **nextNonce)
66 {
67         _INNER_FUNC_ENTER;
68
69         DM_ERROR ret = DM_OK;
70
71         retvm_if((pServer_id) == NULL, COMMON_ERR_IS_NULL, "pServer_id is NULL!!");
72
73         char *authType = NULL;
74         ret = get_client_dmacc(pServer_id, client_id, client_pwd, sourceUrl, targetUrl, isBase64, nextNonce, &authType);
75         if (ret != DM_OK)
76                 goto error;
77
78         _DEBUG_VERBOSE(" end\n");
79         _INNER_FUNC_EXIT;
80         return ret;
81  error:
82         _DEBUG_VERBOSE(" error end [%d]\n", ret);
83         _INNER_FUNC_EXIT;
84         return ret;
85 }
86
87 static DM_ERROR ___generater_deviceInfo_replacecmd(Command ** pReplaceCommand)
88 {
89         _INNER_FUNC_ENTER;
90
91         DM_ERROR ret = DM_OK;
92
93         /*get DevInfo */
94         Item *pItem = NULL;
95         ret = get_child_mo_list(DM_DEVINFO, &(*pReplaceCommand)->private.change.items);
96         if (ret != DM_OK)
97                 goto error;
98
99         GList *iter = NULL;
100         for (iter = (*pReplaceCommand)->private.change.items; iter != NULL; iter = g_list_next(iter)) {
101                 pItem = iter->data;
102                 pItem->contenttype = g_strdup(ELEMENT_TEXTPLAIN);
103                 pItem->format = g_strdup(ELEMENT_CHR);
104         }
105
106         _INNER_FUNC_EXIT;
107         return ret;
108
109  error:
110         _DEBUG_VERBOSE(" error end\n");
111         _INNER_FUNC_EXIT;
112         return ret;
113
114 }
115
116 static DM_ERROR __create_devinfo_replace_cmd(Session * session, Command ** pCommand)
117 {
118         _INNER_FUNC_ENTER;
119
120         DM_ERROR ret = DM_OK;
121         retvm_if((session) == NULL, COMMON_ERR_IS_NULL, "session is NULL!!");
122
123         ret = create_replace_cmd(session, pCommand);
124         if (ret != DM_OK)
125                 goto error;
126
127         ret = ___generater_deviceInfo_replacecmd(pCommand);
128         if (ret != DM_OK)
129                 goto error;
130
131         _INNER_FUNC_EXIT;
132         return ret;
133  error:
134         _DEBUG_VERBOSE(" error : %d\n", ret);
135         _INNER_FUNC_EXIT;
136         return ret;
137
138 }
139
140 static DM_ERROR _generate_setupphase_msg(Session ** session, char *pServer_id, char *pSession_id, int session_type, char **msg, unsigned int *msg_size)
141 {
142         _INNER_FUNC_ENTER;
143
144         DM_ERROR ret = DM_OK;
145
146         retvm_if((pServer_id) == NULL, COMMON_ERR_IS_NULL, "pServer_id is NULL!!");
147
148         int isFinal = 1;
149
150         /*Client init */
151         if (pSession_id == NULL)
152                 pSession_id = g_strdup_printf("%ld", time(NULL));
153
154         char *sourceUrl = NULL;
155         char *client_id = NULL;
156         char *client_pwd = NULL;
157         char *targetUrl = NULL;
158         int isBase64 = 0;
159         char *nextNonce = NULL;
160
161         ret = __get_dmaccInfo(pServer_id, &client_id, &client_pwd, &sourceUrl, &targetUrl, &isBase64, &nextNonce);
162         if (ret != DM_OK)
163                 goto error;
164
165         if (nextNonce == NULL) {
166                 (nextNonce) = strdup(ELEMENT_DEFAULT_CLIENT_NONCE);
167         }
168
169         if ((*session) == NULL) {
170                 ret = create_syncml_session(VERSION_12, PROTOCOL_TYPE_DM, pServer_id, client_id, pSession_id, sourceUrl, targetUrl, session);
171                 if (ret != DM_OK)
172                         goto error;
173         } else {
174                 (*session)->msgID = 0;
175
176 #ifdef _DM_BUNDANG_TEST
177                 /*redirection code */
178                 if ((*session)->target->locURI != NULL) {
179                         char *replace = NULL;
180                         replace = get_new_uri((*session)->target->locURI);
181                         str_free(&((*session)->target->locURI));
182                         (*session)->target->locURI = g_strdup(replace);
183                         str_free(&replace);
184                         _DEBUG_TRACE(" targer url : %s \n", (*session)->target->locURI);
185                 }
186 #endif
187                 isBase64 = 1;
188         }
189
190         _DEBUG_TRACE(" targer url : %s \n", (*session)->target->locURI);
191         ret = __create_authentication(session, client_id, client_pwd, isBase64, nextNonce);
192         if (ret != DM_OK)
193                 goto error;
194
195         _DEBUG_TRACE("targer url : %s \n", (*session)->target->locURI);
196
197         GList *commands = NULL;
198         GList *commands_last = NULL;
199
200         /*SyncHdr */
201         SyncHdr *pSyncHdr = NULL;
202         ret = create_syncml_hdr((*session), &pSyncHdr);
203         if (ret != DM_OK)
204                 goto error;
205
206         /*SyncBody */
207         /* create alert */
208         AlertType syncType;
209         switch (session_type) {
210         case 0:         //IP_PUSH_EVENT
211         case 1:         //WAP_PUSH_EVENT
212                 syncType = DM_ALERT_SERVER_INITIATED_MGMT;
213                 break;
214         case 2:         //UI_EVENT
215         case 3:         //SERVER_BOOTSTRAP_EVENT
216                 syncType = DM_ALERT_CLIENT_INITIATED_MGMT;
217                 break;
218         default:
219                 syncType = DM_ALERT_CLIENT_INITIATED_MGMT;
220                 break;
221         }
222
223         Command *pAlertCommand = NULL;
224         ret = create_alert_cmd((*session), syncType, &pAlertCommand);
225         if (ret != DM_OK)
226                 goto error;
227         putCmdIntoList(&commands, &commands_last, pAlertCommand);
228
229         /* create replace */
230         Command *pReplaceCommand = NULL;
231         ret = __create_devinfo_replace_cmd((*session), &pReplaceCommand);
232         if (ret != DM_OK)
233                 goto error;
234         putCmdIntoList(&commands, &commands_last, pReplaceCommand);
235
236         /*create SyncML */
237         SyncML *pSyncML = NULL;
238         ret = create_syncml(pSyncHdr, NULL, commands, isFinal, &pSyncML);
239         if (ret != DM_OK)
240                 goto error;
241
242         /* convert Msg */
243         ret = syncml_objectbinder(pSyncML, msg, msg_size);
244         if (ret != DM_OK)
245                 goto error;
246
247         /*xml */
248 /*      xml_len = remove_xml_header(xml, xml_len);
249         _DEBUG_TRACE("msg : %s", msg);
250         ret = check_hmac( session,  xml, xml_len);*/
251
252         /*wbxml */
253         _DEBUG_TRACE("msg : %s", msg);
254         ret = __check_hmac(session, *msg, *msg_size);
255         _DEBUG_TRACE(" check hmac:%d\n", ret);
256
257         //free generate structure
258         free_syncml(pSyncML);
259         pSyncML = NULL;
260
261         //session->status, session->alertCommand are already freed in free_SyncML function
262         (*session)->status = NULL;
263
264         if ((*session)->alertCommand != NULL) {
265                 g_list_free((*session)->alertCommand);
266                 (*session)->alertCommand = NULL;
267         }
268
269         (*session)->isSendingfinal = isFinal;
270
271         _INNER_FUNC_EXIT;
272         return ret;
273
274  error:
275
276         _DEBUG_TRACE(" error : %d\n", ret);
277         _INNER_FUNC_EXIT;
278         return ret;
279 }
280
281 static DM_ERROR _generate_management_msg(Session ** session, char **msg, unsigned int *msg_size)
282 {
283         _INNER_FUNC_ENTER;
284
285         DM_ERROR ret = DM_OK;
286
287         retvm_if((*session) == NULL, COMMON_ERR_IS_NULL, "session is NULL!!");
288
289         sync_agent_pb_protocol_binder_function_set_s *pBinder_function_set = NULL;
290         sync_agent_pb_error_e err = init_syncml_binder_function_set(&pBinder_function_set);
291
292         SyncML *pSyncML = NULL;
293         SyncHdr *pSyncHdr = NULL;
294
295         GList *commands = NULL;
296         GList *commands_last = NULL;
297         int isFinal = 1;
298         bool cancel_flag = false;
299
300         GList *status_iter = NULL;
301         Status *pStatus = NULL;
302
303         Command *pAlertCommand = NULL;
304         GList *alert_iter = NULL;
305
306         GList *results_iter = NULL;
307         Command *pResultsCommand = NULL;
308         Command *restResultsCommand = NULL;
309
310         unsigned int estimate_size = 0;
311         int data_size = 0;
312
313         GList *results_data_iter = NULL;
314         GList *rest_result_data_iter = NULL;
315
316         Item *result_item = NULL;
317         Item *rest_result_item = NULL;
318         char *result_data = NULL;
319         int full_msg = 0;
320
321         sync_agent_pb_protocol_binder_info_s *pBinder = NULL;
322         pBinder = syncml_binder_init(pBinder, SYNC_AGENT_PB_ENCODING_WBXML_12, false, true, pBinder_function_set);
323
324 #ifdef _DM_BUNDANG_TEST
325         /*redirection code */
326         if ((*session)->target->locURI != NULL) {
327                 char *replace = NULL;
328                 replace = get_new_uri((*session)->target->locURI);
329                 str_free(&((*session)->target->locURI));
330                 (*session)->target->locURI = g_strdup(replace);
331                 str_free(&replace);
332
333                 _DEBUG_TRACE(" targer url : %s \n", (*session)->target->locURI);
334         }
335 #endif
336
337         /* create SyncHdr */
338         ret = create_syncml_hdr((*session), &pSyncHdr);
339         if (ret != DM_OK)
340                 goto error;
341         err = syncml_binder_append(pBinder, PE_SYNCML_START, NULL);
342         err = syncml_binder_append(pBinder, PE_HEADER, pSyncHdr);
343         err = syncml_binder_append(pBinder, PE_BODY_START, NULL);
344
345 /*      ExecuteObject ** responseObj = (ExecuteObject*) pResponseObj;*/
346         for (status_iter = (*session)->status; status_iter != NULL; status_iter = g_list_next(status_iter)) {
347                 _DEBUG_TRACE("======================================status command================================\n");
348                 pStatus = status_iter->data;
349                 err = syncml_binder_append(pBinder, PE_STATUS, pStatus);
350         }
351
352         //if we have to send alert command(1222,1223 etc)
353         cancel_flag = sync_agent_check_cancel_flag();
354         _DEBUG_TRACE("======================================alert command================================\n");
355         _DEBUG_TRACE("======================================%d================================\n", cancel_flag);
356
357         if (cancel_flag != 0) {
358                 ret = create_alert_cmd((*session), DM_ALERT_SESSION_ABORT, &pAlertCommand);
359                 if (ret != DM_OK)
360                         goto error;
361                 putCmdIntoList(&commands, &commands_last, pAlertCommand);
362                 err = syncml_binder_append(pBinder, PE_ALERT, pAlertCommand);
363         }
364
365         for (alert_iter = (*session)->alertCommand; alert_iter != NULL; alert_iter = g_list_next(alert_iter)) {
366                 _DEBUG_TRACE("======================================alert command================================\n");
367                 pAlertCommand = alert_iter->data;
368                 putCmdIntoList(&commands, &commands_last, pAlertCommand);
369                 err = syncml_binder_append(pBinder, PE_ALERT, pAlertCommand);
370         }
371
372         _DEBUG_TRACE(" server maxsize : %d ", (*session)->targetMaxMsgSize);
373         if ((*session)->resultsCommand != NULL) {
374                 _DEBUG_TRACE("result command length : %d ", g_list_length((*session)->resultsCommand));
375
376                 _DEBUG_TRACE("======================================result command================================\n");
377                 for (results_iter = (*session)->resultsCommand; results_iter != NULL;) {
378                         _DEBUG_TRACE("resultcommand iter");
379                         pResultsCommand = results_iter->data;
380
381                         sync_agent_get_stream_size_from_protocol_binder(pBinder, &estimate_size);
382                         _DEBUG_TRACE("msg extimate size : %d ", estimate_size);
383
384                         ret = duplicate_command(pResultsCommand, &restResultsCommand);
385                         _DEBUG_TRACE("dupicate command : %d", ret);
386                         if (ret != DM_OK) {
387                                 goto error;
388                         }
389
390                         results_iter = g_list_next(results_iter);
391
392                         for (results_data_iter = pResultsCommand->private.results.items, rest_result_data_iter = restResultsCommand->private.results.items; results_data_iter != NULL && rest_result_data_iter != NULL;) {
393                                 _DEBUG_TRACE("resultcommand item iter");
394
395                                 result_item = (Item *) (results_data_iter->data);
396                                 rest_result_item = (Item *) (rest_result_data_iter->data);
397
398                                 result_data = result_item->private.data;
399
400                                 results_data_iter = g_list_next(results_data_iter);
401                                 rest_result_data_iter = g_list_next(rest_result_data_iter);
402
403                                 if (full_msg == 1) {
404                                         _DEBUG_TRACE("remove item because msg size over");
405                                         pResultsCommand->private.results.items = g_list_remove(pResultsCommand->private.results.items, result_item);
406                                 } else {
407                                         _DEBUG_TRACE("result item add packet");
408                                         if (result_item->moreData == 1) {
409                                                 _DEBUG_TRACE("item msg cut by largeObject");
410                                                 isFinal = 0;
411
412                                                 char *data = NULL;
413                                                 int maxsize = 0;
414                                                 data = strdup(result_data);
415
416                                                 str_free(&(result_item->private.data));
417                                                 str_free(&(rest_result_item->private.data));
418
419                                                 maxsize = (*session)->targetMaxMsgSize - estimate_size - DEFAULT_REST_SIZE;
420                                                 _DEBUG_TRACE("maxsize : %d", maxsize);
421
422                                                 result_item->private.data = (char *)calloc(1, maxsize + 1);
423                                                 if (result_item->private.data == NULL) {
424                                                         _DEBUG_TRACE("alloc fail");
425                                                         ret = COMMON_ERR_ALLOC;
426                                                         goto error;
427                                                 }
428                                                 memcpy(result_item->private.data, data, maxsize);
429
430                                                 _DEBUG_TRACE("rest data size : %d", result_item->size - maxsize);
431                                                 rest_result_item->private.data = (char *)calloc(1, result_item->size - maxsize + 1);
432                                                 if (rest_result_item->private.data == NULL) {
433                                                         _DEBUG_TRACE("alloc fail");
434                                                         ret = COMMON_ERR_ALLOC;
435                                                         goto error;
436                                                 }
437                                                 memcpy(rest_result_item->private.data, data + maxsize, result_item->size - maxsize);
438                                                 rest_result_item->size = result_item->size - maxsize;
439
440                                                 if (maxsize > result_item->size - maxsize) {
441                                                         _DEBUG_TRACE("set msg non more data");
442                                                         rest_result_item->moreData = 0;
443                                                 }
444
445                                                 data_size += maxsize;
446                                                 _DEBUG_TRACE("msg(moredata) data size : %d ", data_size);
447
448                                                 full_msg = 1;
449                                         } else {
450                                                 _DEBUG_TRACE("remove item temp list");
451                                                 data_size += result_item->size;
452
453                                                 _DEBUG_TRACE("msg data size : %d ", data_size);
454                                                 restResultsCommand->private.results.items = g_list_remove(restResultsCommand->private.results.items, rest_result_item);
455                                         }
456                                 }
457                         }
458
459                         /*multiple msg */
460                         _DEBUG_TRACE(" ESTIMATE SIZE IN RESULTS= %d", estimate_size + data_size + DEFAULT_REST_SIZE);
461                         if ((*session)->targetMaxMsgSize >= estimate_size + data_size + DEFAULT_REST_SIZE) {
462                                 _DEBUG_TRACE("insert result in msg");
463                                 putCmdIntoList(&commands, &commands_last, pResultsCommand);
464                                 (*session)->resultsCommand = g_list_remove((*session)->resultsCommand, pResultsCommand);
465
466                                 err = syncml_binder_append(pBinder, PE_RESULTS_START, pResultsCommand);
467                                 err = syncml_binder_append(pBinder, PE_RESULTS_END, NULL);
468
469                         } else {
470                                 /*large object */
471                                 isFinal = 0;
472                                 _DEBUG_TRACE("cut result in msg");
473
474                                 if (full_msg == 1) {
475                                         _DEBUG_TRACE("msg msg over large object");
476                                 } else {
477                                         _DEBUG_TRACE("msg cut by MultiMsg");
478                                 }
479                                 _DEBUG_TRACE("free rest result command");
480                                 /*while break */
481                                 break;
482                         }
483
484                         if (full_msg == 1) {
485                                 /*large object rest part preapend in resultsCommands list for next msg */
486                                 if (g_list_length(restResultsCommand->private.results.items) > 0) {
487                                         (*session)->resultsCommand = g_list_prepend((*session)->resultsCommand, restResultsCommand);
488                                 }
489                                 _DEBUG_TRACE("msg cut by MultiMsg");
490                                 break;
491                         } else {
492                                 free_command(restResultsCommand);
493                                 restResultsCommand = NULL;
494                                 _DEBUG_TRACE("free rest result command");
495                         }
496                 }
497                 _DEBUG_TRACE("added result command");
498         }
499
500         /*syncml */
501         ret = create_syncml(pSyncHdr, (*session)->status, commands, isFinal, &pSyncML);
502         if (ret != DM_OK)
503                 goto error;
504
505         _DEBUG_TRACE("final element : %d", isFinal);
506         if (isFinal == 1) {
507                 err = syncml_binder_append(pBinder, PE_FINAL, NULL);
508         }
509
510         err = syncml_binder_append(pBinder, PE_BODY_END, NULL);
511         err = syncml_binder_append(pBinder, PE_SYNCML_END, NULL);
512
513         syncml_binder_get_stream(pBinder, msg, msg_size);
514
515         char *xml = NULL;
516         unsigned int xml_size = 0;
517         err = sync_agent_get_xml_from_protocol_binder(pBinder, &xml, &xml_size);
518         if (err == SYNC_AGENT_PB_RETURN_OK) {
519                 fprintf(stderr, " msg from client \n");
520                 if (fputs(xml, stderr) == EOF) {
521                         _DEBUG_TRACE("debuging test error");
522                 }
523                 set_xml_to_file(xml, OMA_DM_MSG_PATH);
524                 str_free(&xml);
525         }
526
527         syncml_binder_terminate(pBinder);
528
529         /*xml */
530 /*      xml_len = remove_xml_header(xml, xml_len);
531         _DEBUG_TRACE("msg : %s", msg);
532         ret = check_hmac( session,  xml, xml_len);*/
533
534         /*wbxml */
535         ret = __check_hmac(session, *msg, *msg_size);
536         _DEBUG_TRACE(" check hmac:%d\n", ret);
537
538         free_syncml(pSyncML);
539         pSyncML = NULL;
540
541         //session->status, session->alertCommand are already freed in free_SyncML function
542         (*session)->status = NULL;
543         if ((*session)->alertCommand != NULL) {
544                 g_list_free((*session)->alertCommand);
545                 (*session)->alertCommand = NULL;
546         }
547         if (isFinal == 1) {
548                 g_list_free((*session)->resultsCommand);
549                 (*session)->resultsCommand = NULL;
550         }
551
552         (*session)->isSendingfinal = isFinal;
553
554         _INNER_FUNC_EXIT;
555         return ret;
556
557  error:
558         free_command(restResultsCommand);
559         restResultsCommand = NULL;
560
561         free_synchdr(pSyncHdr);
562         pSyncHdr = NULL;
563
564         free_syncml(pSyncML);
565         pSyncML = NULL;
566
567         _DEBUG_TRACE(" error :%d\n", ret);
568
569         _INNER_FUNC_EXIT;
570         return ret;
571
572         //1500 -> ERROR_INTERNAL_OK : generatePreSyncMsg has been completed without any error
573         //1512 -> ERROR_INTERNAL_NO_MEMORY : failed to allocate memory
574         //1513 -> ERROR_INTERNAL_NOT_DEFINED : something is not defined that must have
575         //1503 -> ERROR_INTERNAL_BINDER_ERROR   : binder error
576 }
577
578 DM_ERROR __check_hmac(Session ** session, char *xml, unsigned int xml_len)
579 {
580         _INNER_FUNC_ENTER;
581
582         DM_ERROR ret = DM_OK;
583
584         retvm_if((xml) == NULL, COMMON_ERR_IS_NULL, "xml is NULL!!");
585         retvm_if((*session) == NULL, COMMON_ERR_IS_NULL, "session is NULL!!");
586
587         AuthType auth_type = AUTH_TYPE_UNKNOWN;
588         sync_agent_dm_mo_error_e err_code = SYNC_AGENT_DM_MO_SUCCESS;
589         sync_agent_dm_acc_info_s *acc_info = NULL;
590         sync_agent_dm_mo_acc_item_info_s sync_agent_mo_acc_info_item;
591
592         sync_agent_mo_acc_info_item.acc_type = DEVICE_MANAGE_ACC_TYPE_CLIENT;
593         sync_agent_mo_acc_info_item.serverid = (*session)->pServer_id;
594
595         err_code = sync_agent_get_mo_acc_item(&sync_agent_mo_acc_info_item, &acc_info);
596         //acc_info = sync_agent_get_acc_info(pServer_id, DEVICE_MANAGE_ACC_TYPE_CLIENT);
597         if (err_code != SYNC_AGENT_DM_MO_SUCCESS || acc_info == NULL) {
598                 _DEBUG_VERBOSE(" acc null!!\n");
599                 ret = COMMON_ERR_IS_NULL;
600                 goto error;
601         }
602
603         _DEBUG_VERBOSE(" id = %s\n", acc_info->auth_name);
604         _DEBUG_VERBOSE(" pwd = %s\n", acc_info->auth_secret);
605         _DEBUG_VERBOSE(" serverUrl = %s\n", acc_info->addr);
606         _DEBUG_VERBOSE(" nextNonce = %s\n", acc_info->auth_data);
607
608         if ((acc_info->auth_name) == NULL || (acc_info->auth_secret) == NULL || (acc_info->addr) == NULL) {
609                 ret = COMMON_ERR_IS_NULL;
610                 goto error;
611         }
612
613         auth_type = __get_Session_AuthType_enum(acc_info->auth_type);
614         if (auth_type == AUTH_TYPE_HMAC) {
615
616                 _DEBUG_VERBOSE("auth name : %s", acc_info->auth_name);
617                 _DEBUG_VERBOSE("auth secret : %s", acc_info->auth_secret);
618                 _DEBUG_VERBOSE("auth data : %s", acc_info->auth_data);
619 /*               _DEBUG_VERBOSE("xml : %s", xml);
620                  _DEBUG_VERBOSE("xml_len : %d", xml_len);*/
621
622                 unsigned char *nonce = NULL;
623                 unsigned int nonce_size = 0;
624                 ret = nonce_decode(acc_info->auth_data, &nonce, &nonce_size);
625                 _DEBUG_VERBOSE("nonce result : %d", ret);
626                 _DEBUG_VERBOSE("nonce : %s, noncesize : %d", nonce, nonce_size);
627
628                 char *mac = NULL;
629                 ret = gemerate_hmac(acc_info->auth_name, acc_info->auth_secret, nonce, nonce_size, xml, xml_len, &mac);
630                 if (ret != DM_OK)
631                         goto error;
632                 _DEBUG_VERBOSE("mac : %s", mac);
633
634                 ret = create_hmac(acc_info->auth_name, "MD5", mac, session);
635                 str_free(&mac);
636                 if (ret != DM_OK)
637                         goto error;
638         } else {
639                 _DEBUG_VERBOSE(" auth type : [%d] \n", auth_type);
640         }
641
642         sync_agent_free_mo_acc_item(&acc_info);
643
644         _INNER_FUNC_EXIT;
645         return ret;
646  error:
647
648         sync_agent_free_mo_acc_item(&acc_info);
649
650         _INNER_FUNC_EXIT;
651         _DEBUG_VERBOSE(" end : %d", ret);
652         return ret;
653 }
654
655 static DM_ERROR __create_authentication(Session ** session, char *client_id, char *client_pwd, int isBase64, char *nextNonce)
656 {
657         _INNER_FUNC_ENTER;
658
659         DM_ERROR ret = DM_OK;
660
661         retvm_if((*session) == NULL, COMMON_ERR_IS_NULL, "session is NULL!!");
662         retvm_if((client_id) == NULL, COMMON_ERR_IS_NULL, "client_id is NULL!!");
663
664         Cred *pCred = NULL;
665         Chal *chal = (*session)->res_chal;
666         FormatType formatType = FORMAT_TYPE_UNKNOWN;
667         AuthType pAuthType = AUTH_TYPE_UNKNOWN;
668         char *credData = NULL;
669
670         ret = get_dmacc_authType((*session)->pServer_id, &pAuthType);
671         if (ret != DM_OK)
672                 goto error;
673         _DEBUG_VERBOSE(" pAuthType : [%d] \n", pAuthType);
674
675         if (chal == NULL) {
676                 _DEBUG_VERBOSE("CHAL DOES NOT EXIST\n");
677
678                 unsigned int out_len = 0;
679                 unsigned char *nextNonceDecode = NULL;
680
681                 switch (pAuthType) {
682                 case AUTH_TYPE_BASIC:{
683                                 formatType = FORMAT_TYPE_BASE64;
684                         }
685                         break;
686                 case AUTH_TYPE_MD5:
687                 case AUTH_TYPE_HMAC:
688                         {
689                                 if (isBase64 == 1)
690                                         formatType = FORMAT_TYPE_BASE64;
691                                 else
692                                         formatType = FORMAT_TYPE_UNKNOWN;
693
694                                 if (nextNonce != NULL) {
695                                         _DEBUG_VERBOSE("nextnonce : %s", nextNonce);
696                                         ret = nonce_decode(nextNonce, &nextNonceDecode, &out_len);
697                                         _DEBUG_VERBOSE("nonce result : %d", ret);
698                                         _DEBUG_VERBOSE("nextnoncedecode : %s out len : %d", nextNonceDecode, out_len);
699                                 } else {
700                                         pAuthType = AUTH_TYPE_BASIC;
701                                         formatType = FORMAT_TYPE_BASE64;
702                                 }
703                                 if (pAuthType == AUTH_TYPE_HMAC) {
704                                         (*session)->isHMAC = 1;
705
706                                 }
707                         }
708                         break;
709                 default:
710                         break;
711                 }
712                 _DEBUG_VERBOSE(" client id : %s , client pwd : %s\n", client_id, client_pwd);
713
714                 ret = create_auth_credString(pAuthType, client_id, client_pwd, nextNonceDecode, out_len, &credData);
715                 if (ret != DM_OK)
716                         goto error;
717
718                 ret = create_auth_cred(client_id, client_pwd, pAuthType, formatType, credData, &pCred);
719                 if (ret != DM_OK)
720                         goto error;
721
722         } else {
723                 _DEBUG_VERBOSE("CHAL DOES  EXIST\n");
724
725                 unsigned int out_len = 0;
726                 unsigned char *nextNonceDecode = NULL;
727
728                 if ((*session)->res_chal->type == AUTH_TYPE_HMAC) {
729                         (*session)->isHMAC = 1;
730
731                 } else {
732                         (*session)->isHMAC = 0;
733                 }
734
735                 if (chal->nonce_plain != NULL) {
736                         _DEBUG_VERBOSE("chal->nonce_plain : %s", chal->nonce_plain);
737                         ret = nonce_decode(chal->nonce_plain, &nextNonceDecode, &out_len);
738                         _DEBUG_VERBOSE("nonce result : %d", ret);
739                         _DEBUG_VERBOSE("nextnonceDecode : %s, out len : %d", nextNonceDecode, out_len);
740                         if (ret != DM_OK)
741                                 goto error;
742                 }
743                 ret = create_auth_credString(chal->type, client_id, client_pwd, chal->type == AUTH_TYPE_BASIC ? (const unsigned char *)(chal->nonce_b64) : (const unsigned char *)(nextNonceDecode), out_len, &credData);
744                 if (ret != DM_OK)
745                         goto error;
746
747                 ret = create_auth_cred(client_id, client_pwd, chal->type, chal->format, credData, &pCred);
748                 if (ret != DM_OK)
749                         goto error;
750         }
751         str_free(&credData);
752
753         ret = set_session_authcred((*session), pCred);
754         if (ret != DM_OK)
755                 goto error;
756
757         _INNER_FUNC_EXIT;
758         return ret;
759  error:
760         _DEBUG_VERBOSE(" end error %d \n", ret);
761         _INNER_FUNC_EXIT;
762         return ret;
763 }
764
765 static DM_ERROR _generate_generic_alert(Session ** session, char *pServer_id, char *pSession_id, char **msg, int *msg_size, int service_engine_id, int result)
766 {
767         _INNER_FUNC_ENTER;
768
769         DM_ERROR ret = DM_OK;
770         engine_status *service_status = NULL;
771         int isFinal = 1;
772
773         retvm_if((pServer_id) == NULL, COMMON_ERR_IS_NULL, "pServer_id is NULL!!");
774
775         char *sourceUrl = NULL;
776         char *client_id = NULL;
777         char *client_pwd = NULL;
778         char *targetUrl = NULL;
779         int isBase64 = 0;
780         char *nextNonce = NULL;
781         SyncHdr *pSyncHdr = NULL;
782         Command *pAlertCommand = NULL;
783         char *format = NULL;
784         char *contenttype = NULL;
785         Command *pReplaceCommand = NULL;
786         char *data = NULL;
787         char *pCorrelator = NULL;
788         char *rSourceUrl = NULL;
789
790         /*Client init */
791
792         if ((*session) != NULL) {
793                 _DEBUG_TRACE("session is Exist");
794                 if ((*session)->sessionID != NULL) {
795                         _DEBUG_TRACE("session id : %s", (*session)->sessionID);
796                         pSession_id = (*session)->sessionID;
797                 }
798         } else if (pSession_id == NULL) {
799                 pSession_id = g_strdup_printf("%ld", time(NULL));
800         }
801
802         ret = __get_dmaccInfo(pServer_id, &client_id, &client_pwd, &sourceUrl, &targetUrl, &isBase64, &nextNonce);
803
804         if (ret != DM_OK)
805                 goto error;
806
807         if (nextNonce == NULL) {
808                 (nextNonce) = strdup(ELEMENT_DEFAULT_CLIENT_NONCE);
809         }
810
811         _DEBUG_TRACE(" id = %s\n", client_id);
812         _DEBUG_TRACE(" pwd = %s\n", client_pwd);
813         _DEBUG_TRACE(" Session_id = %s\n", pSession_id);
814         _DEBUG_TRACE(" sourceUrl = %s\n", sourceUrl);
815         _DEBUG_TRACE(" serverUrl = %s\n", targetUrl);
816         _DEBUG_TRACE(" nextNonce = %s\n", nextNonce);
817
818         if ((*session) == NULL) {
819                 ret = create_syncml_session(VERSION_12, PROTOCOL_TYPE_DM, pServer_id, client_id, pSession_id, sourceUrl, targetUrl, session);
820                 if (ret != DM_OK)
821                         goto error;
822         } else {
823                 (*session)->msgID = 0;
824
825 #ifdef _DM_BUNDANG_TEST
826                 /*redirection code */
827                 if ((*session)->target->locURI != NULL) {
828                         char *replace = NULL;
829                         replace = get_new_uri((*session)->target->locURI);
830                         str_free(&((*session)->target->locURI));
831                         (*session)->target->locURI = g_strdup(replace);
832                         str_free(&replace);
833                         _DEBUG_TRACE(" targer url : %s \n", (*session)->target->locURI);
834                 }
835 #endif
836
837                 //nextNonce = g_nextnonce;
838                 //nextNonce = strdup( (*session)->res_chal->nonce_plain);
839                 _DEBUG_TRACE(" NextNonce = %s\n", nextNonce);
840                 isBase64 = 1;
841         }
842
843         ret = __create_authentication(session, client_id, client_pwd, isBase64, nextNonce);
844         if (ret != DM_OK)
845                 goto error;
846
847         /*SyncHdr */
848
849         ret = create_syncml_hdr((*session), &pSyncHdr);
850         if (ret != DM_OK)
851                 goto error;
852
853         GList *commands = NULL;
854         GList *commands_last = NULL;
855
856         /* create alert */
857         ret = create_alert_cmd((*session), DM_ALERT_CLIENT_INITIATED_MGMT, &pAlertCommand);
858         if (ret != DM_OK)
859                 goto error;
860         putCmdIntoList(&commands, &commands_last, pAlertCommand);
861
862         /* create alert */
863         pAlertCommand = NULL;
864         ret = create_alert_cmd((*session), DM_ALERT_GENERIC_ALERT, &pAlertCommand);
865         if (ret != DM_OK)
866                 goto error;
867
868         _DEBUG_TRACE(" service engine status = [%d]\n", service_engine_id);
869
870         ret = Get_Engine_Status(service_engine_id, &service_status);
871         if (ret != DM_OK) {
872                 goto error;
873         }
874
875         _DEBUG_TRACE("STATUS VALUE : %d ", service_status->engine_status);
876         _DEBUG_TRACE("generic alert status data  : %d ", result);
877
878         if (service_status->correlator != NULL) {
879                 pCorrelator = g_strdup(service_status->correlator);
880         }
881         if (service_status->mo_path != NULL) {
882                 rSourceUrl = g_strdup(service_status->mo_path);
883         }
884         if (rSourceUrl == NULL) {
885                 ret = COMMON_ERR_IS_NULL;
886                 goto error;
887         }
888
889         SERVICE_SERVER_TYPE engine_type = get_service_type(rSourceUrl);
890         switch (engine_type) {
891         case SAMSUNG_FUMO_TYPE:
892         case GCF_TYPE:
893                 //format = strdup("chr");//NULL;
894                 //contenttype = strdup("text/plain");//NULL;
895                 contenttype = strdup("org.openmobilealliance.dm.firmwareupdate.downloadandupdate");
896                 break;
897         case SAMSUNG_FMM_TYPE:
898                 contenttype = strdup("urn:oma:at:lawmo:1.0:OperationComplete");
899                 break;
900         default:
901                 break;
902         }
903         //ret =  get_mo_node_format_contenttype(rSourceUrl ,&format, &contenttype );
904
905         data = g_strdup_printf("%d", result);
906         unsigned int size = 0;
907         unsigned int moredata = 0;
908         _DEBUG_TRACE("generic alert status data  : %s ", data);
909
910         Item *pItem = NULL;
911         ret = set_correlator(&pAlertCommand, pCorrelator);
912
913         ret = construct_Item(rSourceUrl, format, contenttype, data, size, moredata, &pItem);
914         pAlertCommand->private.alert.items = g_list_append(pAlertCommand->private.alert.items, pItem);
915         putCmdIntoList(&commands, &commands_last, pAlertCommand);
916
917         /*       create replace */
918         ret = __create_devinfo_replace_cmd((*session), &pReplaceCommand);
919         if (ret != DM_OK)
920                 goto error;
921         putCmdIntoList(&commands, &commands_last, pReplaceCommand);
922
923         /*create SyncML */
924         SyncML *pSyncML = NULL;
925         ret = create_syncml(pSyncHdr, NULL, commands, isFinal, &pSyncML);
926         if (ret != DM_OK)
927                 goto error;
928
929         (*session)->isSendingfinal = isFinal;
930
931         /* convert Msg */
932         ret = syncml_objectbinder(pSyncML, msg, (unsigned int *)msg_size);
933         if (ret != DM_OK)
934                 goto error;
935
936         /*xml */
937 /*      xml_len = remove_xml_header(xml, xml_len);
938         _DEBUG_TRACE("msg : %s", msg);
939         ret = check_hmac( session,  xml, xml_len);*/
940
941         /*wbxml */
942         _DEBUG_TRACE("msg : %s", msg);
943         ret = __check_hmac(session, *msg, *msg_size);
944
945         //free generate structure
946         free_syncml(pSyncML);
947         pSyncML = NULL;
948
949         //session->status, session->alertCommand are already freed in free_SyncML function
950         if ((*session)->resultsCommand != NULL) {
951                 g_list_free((*session)->resultsCommand);
952                 (*session)->resultsCommand = NULL;
953         }
954
955         if ((*session)->alertCommand != NULL) {
956                 g_list_free((*session)->alertCommand);
957                 (*session)->alertCommand = NULL;
958         }
959
960         (*session)->status = NULL;
961         (*session)->isSendingfinal = isFinal;
962
963         Free_Memory_Engine_Status(&service_status, 1);
964
965         str_free(&pCorrelator);
966         str_free(&rSourceUrl);
967         str_free(&data);
968
969         _INNER_FUNC_EXIT;
970         return ret;
971
972  error:
973         if (service_status != NULL)
974                 Free_Memory_Engine_Status(&service_status, 1);
975
976         str_free(&pCorrelator);
977         str_free(&rSourceUrl);
978         str_free((&data));
979
980         _DEBUG_TRACE(" error : %d\n", ret);
981         _INNER_FUNC_EXIT;
982         return ret;
983 }
984
985 DM_ERROR send_msg(char *accType, int transportType, Session ** session, GList * header_info, char *sendMsg, unsigned int sendMsg_length, GList ** recv_header, char **recvMsg, unsigned int *recvMsg_length)
986 {
987         _EXTERN_FUNC_ENTER;
988         DM_ERROR ret = DM_OK;
989
990         retvm_if((accType) == NULL, COMMON_ERR_IS_NULL, "accType is NULL!!");
991         retvm_if((*session) == NULL, COMMON_ERR_IS_NULL, "session is NULL!!");
992         retvm_if((sendMsg) == NULL, COMMON_ERR_IS_NULL, "sendMsg is NULL!!");
993
994         ret = _send_msg(accType, transportType, session, (*session)->target->locURI, header_info, sendMsg, sendMsg_length, recv_header, recvMsg, recvMsg_length);
995         if (ret != DM_OK)
996                 goto error;
997
998         _EXTERN_FUNC_EXIT;
999         return DM_OK;
1000
1001  error:
1002         _DEBUG_INFO(" error : %d\n", ret);
1003
1004         _EXTERN_FUNC_EXIT;
1005         return ret;
1006 }
1007
1008 DM_ERROR recv_msg(Session ** session, char *recvMsg, unsigned int recvMsg_length, ENGINE_ID * service_engine_id, int *isFinish, int isgeneticAlert)
1009 {
1010         _EXTERN_FUNC_ENTER;
1011
1012         DM_ERROR ret = DM_OK;
1013
1014         retvm_if((*session) == NULL, COMMON_ERR_IS_NULL, "session is NULL!!");
1015         retvm_if((recvMsg) == NULL, COMMON_ERR_IS_NULL, "recvMsg is NULL!!");
1016
1017         ret = _recv_msg(session, recvMsg, recvMsg_length, service_engine_id, isFinish, isgeneticAlert);
1018         if (ret != DM_OK)
1019                 goto error;
1020
1021         _EXTERN_FUNC_EXIT;
1022         return DM_OK;
1023
1024  error:
1025         _DEBUG_INFO(" error : %d\n", ret);
1026         _EXTERN_FUNC_EXIT;
1027         return ret;
1028 }
1029
1030 DM_ERROR _send_msg(char *accType, int transportType, Session ** session, char *server_url, GList * header_info, char *sendMsg, unsigned int sendMsg_length, GList ** recv_header, char **recvMsg, unsigned int *recvMsg_length)
1031 {
1032         _INNER_FUNC_ENTER;
1033
1034         sync_agent_na_result_e res = SYNC_AGENT_NA_SUCCESS;
1035         DM_ERROR ret = DM_OK;
1036
1037         retvm_if((*session) == NULL, COMMON_ERR_IS_NULL, "session is NULL!!");
1038         retvm_if((accType) == NULL, COMMON_ERR_IS_NULL, "accType is NULL!!");
1039         retvm_if((server_url) == NULL, COMMON_ERR_IS_NULL, "server_url is NULL!!");
1040         retvm_if((sendMsg) == NULL, COMMON_ERR_IS_NULL, "sendMsg is NULL!!");
1041
1042         int net_session_id = 0;
1043         bool cancel_flag;
1044
1045         _DEBUG_TRACE("server url : %s", server_url);
1046         //timeout : 30 seconds
1047         res = sync_agent_open_connection(transportType, 30, (unsigned int *)(&(net_session_id)));
1048
1049         _DEBUG_TRACE("res =%d\n", res);
1050
1051         if (res != SYNC_AGENT_NA_SUCCESS) {
1052                 ret = COMMON_ERR_INTERNAL_CONNECTION_ERROR;
1053                 goto error;
1054         }
1055
1056         sync_agent_register_cancel_callback(network_cancel_callback, &(net_session_id));
1057
1058         //check cancel flag (note that this can be called every where inside processing logic)
1059         cancel_flag = sync_agent_check_cancel_flag();
1060         if (cancel_flag) {
1061                 ret = DM_ERR_USER_CANDELLED;
1062                 sync_agent_unregister_cancel_callback(network_cancel_callback, &(net_session_id));
1063                 goto returnerror;
1064         }
1065
1066         int err = 0;
1067         if ((*session)->reqhmacinfo != NULL) {
1068                 err = NA_http_header_binder(accType, server_url, (*session)->jsessionid, (*session)->isHMAC, (*session)->reqhmacinfo->username, (*session)->reqhmacinfo->mac, &header_info);
1069         } else {
1070                 err = NA_http_header_binder(accType, server_url, (*session)->jsessionid, (*session)->isHMAC, NULL, NULL, &header_info);
1071         }
1072
1073         if (err != 1) {
1074                 _DEBUG_TRACE("header binding error : %d", err);
1075                 ret = DM_ERR_USER_CANDELLED;
1076                 sync_agent_unregister_cancel_callback(network_cancel_callback, &(net_session_id));
1077                 goto returnerror;
1078         }
1079
1080         res = sync_agent_send_msg(      /*acc_info (id, pw, uri, ...), */
1081                                          header_info, transportType, sendMsg, sendMsg_length, recv_header, (unsigned char **)recvMsg, recvMsg_length, SYNC_AGENT_NA_SEND_TYPE_SEND_N_RECEIVE, net_session_id);
1082         _DEBUG_TRACE("  res =%d\n", res);
1083
1084         sync_agent_unregister_cancel_callback(network_cancel_callback, &(net_session_id));
1085         if (res != SYNC_AGENT_NA_SUCCESS) {
1086                 ret = COMMON_ERR_INTERNAL_CONNECTION_ERROR;
1087                 goto returnerror;
1088         } else {
1089                 cancel_flag = sync_agent_check_cancel_flag();
1090                 if (cancel_flag) {
1091                         ret = DM_ERR_USER_CANDELLED;
1092                         goto returnerror;
1093                 }
1094         }
1095
1096         //_DEBUG_TRACE("recieve http header : %s ", (*recv_header));
1097
1098         _DEBUG_TRACE(" CKECK JSESSION\n");
1099         char *temp_jsessionid = NULL;
1100         char *real_jsessionid = NULL;
1101         char *real_other_cookie = NULL;
1102         res = sync_agent_get_header_info(1, (*recv_header), "Set-Cookie", &temp_jsessionid);
1103         if (res == SYNC_AGENT_NA_SUCCESS) {
1104                 ret = add_jsession_in_httpheader(*recv_header, temp_jsessionid, &real_jsessionid, &real_other_cookie);
1105                 if (ret == DM_OK) {
1106                         if (real_jsessionid != NULL && (*session)->jsessionid != NULL) {
1107                                 if (strcmp((*session)->jsessionid, real_jsessionid) != 0) {
1108                                         str_free(&((*session)->jsessionid));
1109                                         (*session)->jsessionid = strdup(real_jsessionid);
1110                                 } else {
1111                                         str_free(&real_jsessionid);
1112                                 }
1113                         } else {
1114                                 (*session)->jsessionid = strdup(real_jsessionid);
1115                         }
1116
1117                         _DEBUG_TRACE("-------------------------------------------------------------------------------------------------------------------------------------------------");
1118                         _DEBUG_TRACE("jsession id = %s\n", (*session)->jsessionid);
1119                         _DEBUG_TRACE("-------------------------------------------------------------------------------------------------------------------------------------------------");
1120                 }
1121                 ret = DM_OK;
1122         }
1123
1124         char *temp_hmac = NULL;
1125         res = sync_agent_get_header_info(1, (*recv_header), HTTP_X_SYNCML_HMAC, &temp_hmac);
1126         if (res == SYNC_AGENT_NA_SUCCESS) {
1127                 if (temp_hmac != NULL) {
1128                         ret = add_response_hmacinfo(session, temp_hmac);
1129                         if (ret != DM_OK) {
1130                                 res = sync_agent_close_connection(transportType, net_session_id);
1131                                 _DEBUG_TRACE(" %d res =%d\n", __LINE__, res);
1132                                 goto returnerror;
1133                         }
1134                 }
1135         }
1136
1137         res = sync_agent_close_connection(transportType, net_session_id);
1138
1139         _DEBUG_TRACE("res =%d\n", res);
1140         if (res != SYNC_AGENT_NA_SUCCESS) {
1141                 ret = COMMON_ERR_INTERNAL_CONNECTION_ERROR;
1142                 goto returnerror;
1143         }
1144
1145         if (sendMsg != NULL)
1146                 free(sendMsg);
1147
1148         _INNER_FUNC_EXIT;
1149         return ret;
1150
1151  returnerror:
1152         _DEBUG_TRACE(" returnerror = %d\n", ret);
1153
1154         res = sync_agent_close_connection(transportType, net_session_id);
1155         _DEBUG_TRACE(" %d res =%d\n", __LINE__, res);
1156         if (res != SYNC_AGENT_NA_SUCCESS) {
1157                 ret = COMMON_ERR_INTERNAL_CONNECTION_ERROR;
1158                 goto error;
1159         }
1160
1161         if (sendMsg != NULL)
1162                 free(sendMsg);
1163
1164         _INNER_FUNC_EXIT;
1165         return ret;
1166  error:
1167         _DEBUG_TRACE(" error = %d\n", ret);
1168
1169         if (sendMsg != NULL)
1170                 free(sendMsg);
1171
1172         _INNER_FUNC_EXIT;
1173         return ret;
1174 }
1175
1176 static DM_ERROR _recv_msg(Session ** session, char *recvMsg, unsigned int recvMsg_length, ENGINE_ID * service_engine_id, int *isFinish, int isgeneticAlert)
1177 {
1178
1179         _INNER_FUNC_ENTER;
1180         DM_ERROR ret = DM_OK;
1181
1182         retvm_if((*session) == NULL, COMMON_ERR_IS_NULL, "session is NULL!!");
1183         retvm_if((recvMsg) == NULL, COMMON_ERR_IS_NULL, "recvMsg is NULL!!");
1184
1185         reset_cmdid_session((*session));
1186
1187         SyncML *pSyncML = (SyncML *) calloc(1, sizeof(SyncML));
1188         if (pSyncML == NULL) {
1189                 _DEBUG_TRACE("alloc fail");
1190                 ret = COMMON_ERR_ALLOC;
1191                 goto error;
1192         }
1193         char *xml = NULL;
1194         unsigned int xml_len = 0;
1195         ret = reverse_syncml_objectbinder(&pSyncML, recvMsg, recvMsg_length, &xml, &xml_len);
1196         if (ret != DM_OK)
1197                 goto error;
1198
1199         /* check receive msg */
1200         ret = receive_header((*session), pSyncML->hdr);
1201         if (ret != DM_OK)
1202                 goto error;
1203
1204         ret = receive_statuses((*session), pSyncML->status);
1205         if (ret != DM_OK) {
1206                 goto error;
1207         }
1208
1209         /* check that pending list is empty */
1210         GList *o = NULL;
1211         for (o = (*session)->pendingStatus; o != NULL; o = g_list_next(o)) {
1212                 PendingStatus *pending = o->data;
1213                 _DEBUG_TRACE(" in pendingStatus List msgID : %d, cmdID : %d\n", pending->msgID, pending->cmdID);
1214         }
1215
1216         ret = receive_cmd((*session), pSyncML->commands);
1217         if (ret != DM_OK)
1218                 goto error;
1219
1220         /*service engine */
1221         if ((*session)->service_engine_id != NO_SERVICE_ENGINE) {
1222                 *service_engine_id = (*session)->service_engine_id;
1223         }
1224
1225         if (pSyncML->final != 0) {
1226                 (*session)->isSendingfinal = 0;
1227                 (*session)->isReceivingFinal = 1;
1228         } else {
1229                 (*session)->isReceivingFinal = 0;
1230         }
1231
1232         _DEBUG_TRACE("receive final : %d , isgeneticAlert : %d ", (*session)->isReceivingFinal, isgeneticAlert);
1233
1234         if (*session != NULL && (*session)->isReceivingFinal != 0 && ((*session)->status != NULL && g_list_length((*session)->status) == 1 && (*session)->resultsCommand == NULL && isgeneticAlert == 0)) {
1235                 (*isFinish) = 1;
1236                 _DEBUG_TRACE("---------------------------------------------------------------------------recv msg end------------------------------------------------------------------------\n");
1237                 _DEBUG_TRACE("---------------------------------------------------------------------------free session------------------------------------------------------------------------\n");
1238                 free_session((*session));
1239                 *session = NULL;
1240         } else {
1241                 _DEBUG_TRACE("not final");
1242         }
1243
1244         if (recvMsg != NULL)
1245                 free(recvMsg);
1246         if (pSyncML != NULL)
1247                 free_syncml(pSyncML);
1248
1249         _INNER_FUNC_ENTER;
1250         return ret;
1251
1252  error:
1253         _DEBUG_TRACE(" error : %d\n", ret);
1254         if (recvMsg != NULL)
1255                 free(recvMsg);
1256         if (pSyncML != NULL)
1257                 free_syncml(pSyncML);
1258
1259         _INNER_FUNC_ENTER;
1260         return ret;
1261
1262 }
1263
1264 DM_ERROR setup_phase(int transportType, Session ** session, char *pServer_id, char *pSession_id, int session_type, ENGINE_ID * service_engine_id, int *isFinish, int isgenericAlert)
1265 {
1266         _EXTERN_FUNC_ENTER;
1267
1268         DM_ERROR ret = DM_OK;
1269         retvm_if((pServer_id) == NULL, COMMON_ERR_IS_NULL, "pServer_id is NULL!!");
1270
1271         /*generate setupPhase Msg */
1272         char *msg = NULL;
1273         unsigned int msg_size = 0;
1274
1275         /*exchange Msg */
1276         char *recv_msg = NULL;
1277         int recv_msg_size = 0;
1278
1279         GList *recv_header = 0;
1280         GList *list = NULL;
1281         int count = 0;
1282
1283         while (count++ != MAX_SESSION_COUNT) {
1284                 //when errortype is ERROR_AUTH_REQUIRED try request using res_chal just one more time
1285                 //it can be only happend when server required MD5 authentication(we send basic authentication every time by default)
1286                 msg = NULL;
1287                 msg_size = 0;
1288                 ret = _generate_setupphase_msg(session, pServer_id, pSession_id, session_type, &msg, &msg_size);
1289                 if (ret != DM_OK)
1290                         goto error;
1291
1292                 file_count++;
1293                 char file_name[1000];
1294                 /*debuging */
1295                 snprintf(file_name, (int)sizeof(file_name), "/opt/data/oma-dm-cfg/packet/wbxml_send_msg_%d.wbxml", file_count);
1296                 _DEBUG_INFO("file name : %s", file_name);
1297                 sync_agent_write_whole_file(file_name, msg, msg_size, true);
1298
1299                 list = NULL;
1300                 recv_header = NULL;
1301                 ret = _send_msg("OMA_DM", 1, session, (*session)->target->locURI, list, msg, msg_size, &recv_header, &recv_msg, (unsigned int *)(&recv_msg_size));
1302                 if (ret != DM_OK)
1303                         goto error;
1304                 /*debuging */
1305                 snprintf(file_name, (int)sizeof(file_name), "/opt/data/oma-dm-cfg/packet/wbxml_receivce_msg_%d.wbxml", file_count);
1306                 _DEBUG_INFO("file name : %s", file_name);
1307                 sync_agent_write_whole_file(file_name, recv_msg, recv_msg_size, true);
1308
1309                 ret = _recv_msg(session, recv_msg, recv_msg_size, service_engine_id, isFinish, isgenericAlert);
1310                 if (ret != DM_ERR_UNAUTHORIZED && ret != DM_ERR_AUTHENTICATION_REQUIRED) {
1311                         _DEBUG_INFO("  authentication : %d\n ", ret);
1312                         break;
1313                 }
1314
1315                 _DEBUG_INFO("revceive end ======================");
1316
1317         }
1318
1319         if (ret != DM_OK || (*session != NULL && (*session)->status != NULL && (g_list_length((*session)->status) == 1 && (*session)->resultsCommand == NULL && (*session)->alertCommand == NULL && isgenericAlert == 0))) {
1320                 *isFinish = 1;
1321                 _DEBUG_INFO("---------------------------------------------------------------------------recv msg end------------------------------------------------------------------------\n");
1322                 _DEBUG_INFO("---------------------------------------------------------------------------free session------------------------------------------------------------------------\n");
1323                 free_session((*session));
1324                 *session = NULL;
1325                 if (ret != DM_OK)
1326                         goto error;
1327         }
1328
1329         _EXTERN_FUNC_EXIT;
1330         return ret;
1331
1332  error:
1333         _DEBUG_INFO(" end error %d\n", ret);
1334         _EXTERN_FUNC_EXIT;
1335         return ret;
1336 }
1337
1338 DM_ERROR management_phase(int transportType, Session ** session, char *pSession_id, ENGINE_ID * service_engine_id, int *isFinish)
1339 {
1340         _EXTERN_FUNC_ENTER;
1341
1342         DM_ERROR ret = DM_OK;
1343
1344         retvm_if((*session) == NULL, COMMON_ERR_IS_NULL, "session is NULL!!");
1345
1346         while ((*isFinish) == 0) {
1347
1348                 /*generate management phase Msg */
1349                 char *msg = NULL;
1350                 unsigned int msg_size = 0;
1351
1352                 /*exchange Msg */
1353                 char *recvMsg = NULL;
1354                 unsigned int recvMsg_size = 0;
1355                 GList *recv_header = 0;
1356                 GList *list = NULL;
1357
1358                 ret = _generate_management_msg(session, &msg, &msg_size);
1359                 if (ret != DM_OK)
1360                         goto error;
1361                 /*for debuging */
1362                 file_count++;
1363                 char file_name[1000];
1364                 snprintf(file_name, (int)sizeof(file_name), "/opt/data/oma-dm-cfg/packet/wbxml_management_send_msg_%d.wbxml", file_count);
1365                 _DEBUG_INFO("file name : %s", file_name);
1366                 sync_agent_write_whole_file(file_name, msg, msg_size, true);
1367
1368                 ret = send_msg("OMA_DM", 1, session, list, msg, msg_size, &recv_header, &recvMsg, &recvMsg_size);
1369                 if (ret != DM_OK)
1370                         goto error;
1371
1372                 /*for debuging */
1373                 snprintf(file_name, (int)sizeof(file_name), "/opt/data/oma-dm-cfg/packet/wbxml_management_receivce_msg_%d.wbxml", file_count);
1374                 _DEBUG_INFO("file name : %s", file_name);
1375                 sync_agent_write_whole_file(file_name, recvMsg, recvMsg_size, true);
1376
1377                 ret = recv_msg(session, recvMsg, recvMsg_size, service_engine_id, isFinish, 0);
1378                 if (ret != DM_OK)
1379                         goto error;
1380
1381                 _DEBUG_INFO(" end  : %d \n", ret);
1382
1383         }
1384         _EXTERN_FUNC_EXIT;
1385         return ret;
1386
1387  error:
1388         _DEBUG_INFO(" error : %d end \n", ret);
1389         _EXTERN_FUNC_EXIT;
1390         return ret;
1391 }
1392
1393 DM_ERROR generic_alert(int transportType, Session ** session, char *pServer_id, char *pSession_id, int *isFinish, int isgeneticAlert, ENGINE_ID service_engine_id, int result)
1394 {
1395         _EXTERN_FUNC_ENTER;
1396
1397         DM_ERROR ret = DM_OK;
1398
1399         /*generate setupPhase Msg */
1400         char *msg = NULL;
1401         unsigned int msg_size = 0;
1402
1403         /*exchange Msg */
1404         GList *list = NULL;
1405         char *recvMsg = NULL;
1406         unsigned int recvMsg_size = 0;
1407         GList *recv_header = 0;
1408
1409         int count = 0;
1410         while (count++ != MAX_SESSION_COUNT) {
1411
1412                 msg = NULL;
1413                 msg_size = 0;
1414                 ret = _generate_generic_alert(session, pServer_id, pSession_id, &msg, (int *)(&msg_size), service_engine_id, result);
1415                 if (ret != DM_OK)
1416                         goto error;
1417
1418                 file_count++;
1419                 char file_name[1000];
1420
1421                 snprintf(file_name, (int)sizeof(file_name), "/opt/data/oma-dm-cfg/packet/wbxml_generic_send_msg_%d.wbxml", file_count);
1422                 _DEBUG_INFO("file name : %s", file_name);
1423                 sync_agent_write_whole_file(file_name, msg, msg_size, true);
1424
1425                 list = NULL;
1426                 recv_header = NULL;
1427                 ret = send_msg("OMA_DM", 1, session, list, msg, msg_size, &recv_header, &recvMsg, &recvMsg_size);
1428                 if (ret != DM_OK)
1429                         goto error;
1430
1431                 snprintf(file_name, (int)sizeof(file_name), "/opt/data/oma-dm-cfg/packet/wbxml_generic_receivce_msg_%d.wbxml", file_count);
1432                 _DEBUG_INFO("file name : %s", file_name);
1433                 sync_agent_write_whole_file(file_name, recvMsg, recvMsg_size, true);
1434
1435                 ret = recv_msg(session, recvMsg, recvMsg_size, &service_engine_id, isFinish, isgeneticAlert);
1436                 _DEBUG_INFO(" Recv_Msg : %d count : %d \n ", ret, count);
1437
1438                 if (ret != DM_ERR_UNAUTHORIZED && ret != DM_ERR_AUTHENTICATION_REQUIRED) {
1439                         _DEBUG_INFO(" generic alert authentication : %d\n ", ret);
1440                         break;
1441                 }
1442         }
1443
1444         _DEBUG_INFO(" end  : %d \n", ret);
1445         _EXTERN_FUNC_EXIT;
1446         return ret;
1447  error:
1448         _DEBUG_INFO(" error : %d end \n", ret);
1449         _EXTERN_FUNC_EXIT;
1450         return ret;
1451 }